Subclassing socket
Bryan Olson
fakeaddress at nowhere.org
Fri Jan 13 18:59:59 EST 2006
groups.20.thebriguy at spamgourmet.com wrote:
> To your question of why you'd ever [recv(0)].
>
> This is very common in any network programming. If you send a packet
> of data that has a header and payload, and the header contains the
> length (N) of the payload, then at some point you have to receive N
> bytes. If N is zero, then you receive 0 bytes. Of course, you CAN
> test for N == 0, that's obvious - but why would you if the underlying
> layers worked correctly? Its just extra code to handle an special case.
We need "extra code" around recv to ensure we get exactly
N bytes; 'recv(N)' can return less. The most straightforward
code I know to read exactly N bytes never passes zero to
recv (untested):
def recvall(sock, size):
""" Read and return exactly 'size' bytes from socket 'sock'.
Kind of the other side of sock.sendall.
"""
parts = []
while size > 0:
data = sock.recv(size)
if not data:
raise SomeException("Socket closed early.")
size -= len(data)
parts.append(data)
return ''.join(parts)
--
--Bryan
More information about the Python-list
mailing list