Receive data from socket stream

Hrvoje Niksic hniksic at xemacs.org
Mon Apr 28 05:42:45 EDT 2008


Nick Craig-Wood <nick at craig-wood.com> writes:

> What you are missing is that if the recv ever returns no bytes at all
> then the other end has closed the connection.  So something like this
> is the correct thing to write :-
>
>   data = ""
>   while True:
>       new = client.recv(256)
>       if not new:
>           break
>       data += new

This is a good case for the iter() function:

buf = cStringIO.StringIO()
for new in iter(partial(client.recv, 256), ''):
    buf.write(new)
data = buf.getvalue()

Note that appending to a string is almost never a good idea, since it
can result in quadratic allocation.



More information about the Python-list mailing list