Buffer size when receiving data through a socket?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Jun 18 08:00:59 CEST 2008

En Tue, 17 Jun 2008 10:34:24 -0300, John Salerno <johnjsal at nospamgmail.com> escribió:

> I was wondering about sendall(). The examples I've read in two different
> books are consistent in their use of send() and don't even mention
> sendall(), so I thought maybe it was for a more specialized situation.

«Stream sockets (e.g., TCP sockets) exhibit a behavior with the read and write functions that differs from normal file I/O. A read or write on a stream socket might input or output fewer bytes than requested, but this is not an error condition. The reason is that buffer limits might be reached for the socket in the kernel. All that is required to input or output the remaining bytes is for the caller to invoke the read or write function again. Some versions of Unix also exhibit this behavior when writing more than 4,096 bytes to a pipe. This scenario is always a possibility on a stream socket with read, but is normally seen with write only if the socket is nonblocking. Nevertheless, we always call our writen function instead of write, in case the implementation returns a short count.» [1]

The Python `sendall` method is equivalent to the `writen` function they refer to. Rather than analyzing in each case whether sendall is to be required or not, I prefer to always use it and forget about it...

> Oh!!!! I didn't even count "You typed:" as part of the 10 bytes! And what a
> coincidence that it happens to be exactly 10 characters! That really helped
> to hide the problem from me!


>> (Note that in this particular configuration, the client will fill its
>> buffer at some time: because the server sends at least 11 bytes each
>> round, but the client reads at most 10 bytes, so the client is always
>> behind the server...)
> How is the server sending back 11 bytes? Is it because it's sending at least
> the 10 characters, plus the extra space?

Yes, 10 + whatever you typed in the client side (at least one character - an empty string exits the program).

[1] Richard Stevens et al.: UNIX Network Programming, Volume 1, Third Edition: The Sockets Networking API. Section 3.9

Gabriel Genellina

More information about the Python-list mailing list