Select weirdness
Irmen de Jong
irmen.NOSPAM at xs4all.nl
Sun Apr 22 06:50:37 EDT 2007
Ron Garret wrote:
> Here's my code. It's a teeny weeny little HTTP server. (I'm not really
> trying to reinvent the wheel here. What I'm really doing is writing a
> dispatching proxy server, but this is the shortest way to illustrate the
> problem I'm having):
>
> from SocketServer import *
> from socket import *
> from select import select
>
> class myHandler(StreamRequestHandler):
> def handle(self):
> print '>>>>>>>>>>>'
> while 1:
> sl = select([self.rfile],[],[])[0]
> if sl:
> l = self.rfile.readline()
> if len(l)<3: break
> print l,
> pass
> pass
> print>>self.wfile, 'HTTP/1.0 200 OK'
> print>>self.wfile, 'Content-type: text/plain'
> print>>self.wfile
> print>>self.wfile, 'foo'
> self.rfile.close()
> self.wfile.close()
> print '<<<<<<<<<<<<'
> pass
> pass
You shouldn't use a select() of your own inside the handle method.
The socketserver takes care of that for you.
What you need to do is read the input from the socket until you've reached
the end-of-input marker. That marker is an empty line containing just "\r\n"
when dealing with HTTP GET requests.
Any reason don't want to use the BasicHTTPServer that comes with Python?
Anyway, try the following instead:
from SocketServer import *
from socket import *
from select import select
class myHandler(StreamRequestHandler):
def handle(self):
print '>>>>>>>>>>>'
while True:
l = self.rfile.readline()
print repr(l)
if not l or l=='\r\n':
break
print>>self.wfile, 'HTTP/1.0 200 OK'
print>>self.wfile, 'Content-type: text/plain'
print>>self.wfile
print>>self.wfile, 'foo'
self.rfile.close()
self.wfile.close()
print '<<<<<<<<<<<<'
def main():
server = TCPServer(('',8080), myHandler)
server.serve_forever()
if __name__ == '__main__': main()
--Irmen
More information about the Python-list
mailing list