Receive data from socket stream

Nick Craig-Wood nick at craig-wood.com
Mon Apr 28 05:30:03 EDT 2008


s0suk3 at gmail.com <s0suk3 at gmail.com> wrote:
>  I wanted to ask for standard ways to receive data from a socket stream
>  (with socket.socket.recv()). It's simple when you know the amount of
>  data that you're going to receive, or when you'll receive data until
>  the remote peer closes the connection. But I'm not sure which is the
>  best way to receive a message with undetermined length from a stream
>  in a connection that you expect to remain open. Until now, I've been
>  doing this little trick:
> 
>  data = client.recv(256)
>  new = data
>  while len(new) == 256:
>      new = client.recv(256)
>      data += new
> 
>  That works well in most cases. But it's obviously error-prone. What if
>  the client sent *exactly* two hundred and fifty six bytes? It would
>  keep waiting for data inside the loop. Is there really a better and
>  standard way, or is this as best as it gets?

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

>From the man page for recv

  RETURN VALUE

       These calls return the number of bytes received, or -1 if an
       error occurred.  The return value will be 0 when the peer has
       performed an orderly shutdown.

In the -1 case python will raise a socket.error.

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list