need a thread to keep a socket connection alive?
Fredrik Lundh
fredrik at pythonware.com
Mon Apr 24 08:39:20 EDT 2006
Roy Smith wrote:
> If you want to read fixed-length messages (as you appear to be trying to do
> with your recv(158)), you need to build a buffering layer which reads from
> the socket into a buffer and then doles out messages to a higher layer from
> that buffer.
> This is not a trivial problem. By the time you're done with it, you will
> have learned a lot about how to communicate over a network.
however, creating a buffered layer for reading is a trivial problem: just call
makefile on the socket object, and use the resulting object as a file handle:
>>> s = socket.socket()
>>> s.connect(("www.python.org", 80))
>>> s.send("GET / HTTP/1.0\n\n")
16
>>> f = s.makefile()
>>> f.readline()
'HTTP/1.1 200 OK\r\n'
>>> f.readline()
'Date: Mon, 24 Apr 2006 12:37:46 GMT\r\n'
>>> f.read(10)
'Server: Ap'
>>> f.read(10)
'ache/2.0.5'
>>> f.readline()
'4 (Debian GNU/Linux) DAV/2 SVN/1.1.4 mod_python/3.1.3 ...
>>> f.readline()
'Last-Modified: Mon, 24 Apr 2006 04:52:53 GMT\r\n'
etc.
</F>
More information about the Python-list
mailing list