socket block ????

Fredrik Lundh fredrik at effbot.org
Fri Jan 5 03:14:14 EST 2001


Eric Hagemann wrote:
> Making use of the socket module, the library manual indicates that the
> default behavior of the module is to block on a read or a write.  But when
> using socket.recv(buf) some times it returns before reading len(buf) bytes.

buffered != blocking

In blocking mode, recv guarantees that it will wait for
*some* data from the other end before it returns.

To get buffered behaviour, use the "makefile" method
to get a buffered file interface to the socket, and read
via that interface.

here's a typical excerpt from a client program:

  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.connect((host, port))
  file = sock.makefile("rb")
  data = file.read(1024) # get first kilobyte from server

in a client, you usually only need to buffer input (to simplify
parsing).  to send data, use unbuffered "send" as usual.  if
you prefer buffered output too, don't forget to "flush" data
before trying to read a response from the server

Hope this helps!

Cheers /F

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->






More information about the Python-list mailing list