Receive data from socket stream

hdante hdante at gmail.com
Fri Apr 25 20:13:02 EDT 2008


On Apr 25, 7:39 pm, 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.
>
> Thanks,
> Sebastian


done = False
remaining = ''
while done == False:
    data = client.recv(256)
    done, remaining = process(remaining + data)

PS: are you sure you shouldn't be using RPC or SOAP ?



More information about the Python-list mailing list