Receive data from socket stream

s0suk3 at gmail.com s0suk3 at gmail.com
Fri Apr 25 18:53:53 EDT 2008


On Apr 25, 5:52 pm, Erik Max Francis <m... at alcyone.com> wrote:
> s0s... 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?
>
> > Sorry if this is a little off-topic and more related to networking,
> > but I'm using Python anyway.
>
> You solve this by having a protocol that the client and server both
> agree on, so that the client knows how much to read from the server.
> There are any number of ways of doing this, all of which depend on the
> kind of data you want to transfer and for what purpose.
>
> --
> Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/
>   San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
>    In the final choice a solider's pack is not so heavy a burden as a
>     prisoner's chains. -- Dwight D. Eisenhower, 1890-1969

So, in an HTTP client/server, I'd had to look in a Content-Length
header?



More information about the Python-list mailing list