A socket question

Robin Munn rmunn at pobox.com
Mon Jan 14 11:25:11 EST 2002


On Sat, 12 Jan 2002 01:22:44 -0600, Jason Orendorff
<jason at jorendorff.com> wrote:
>>   I am not really familiar with sockets.
>> 
>>   However I succeeded in creating a server and client. The client 
>> requests a file that is sent by the server (the contents). On Linux, I 
>> could use MSG_WAITALL option for recv to get all the data.
>> 
>>   Trying this on windows failed because it is not in the socket module 
>> there. [...]
>
>Suppose you have a socket variable "s".
>Once the socket is already connected, you can do
>
>  f = s.makefile('r')
>  all_the_text = f.read()
>  f.close()
>  s.close()

Jason's way is the simplest way of doing what you want. A slightly more
complicated way would be:

readlist = [s]
writelist = []
exceptlist = []
import select
# Wait for s to be ready for reading
ready = select.select(readlist, writelist, exceptlist)
# Fetch all from the socket
buf = ''
while 1:
    data = s.recv(1024)   # Use a larger chunk size if you want
    if not data: break    # recv() returns '' (empty string) at EOF
    buf += data
s.close()

What this code does is call select(), which expects to be passed three
lists. One is a list of sockets to be read from, one is a list of
sockets to be written to, and one is a list of sockets to be checked for
"exceptional conditions" (I don't know what constitutes an "exceptional
condition" on a TCP/IP socket; one of the RFC's should be able to tell
you). An optional fourth parameter specifies a timeout in seconds; no
timeout parameter means wait forever. select() will return immediately
when one of the following occurs:

1) The timeout period runs out.

2) At least one socket in the readlist had data available to be read.

3) At least one socket in the writelist had free buffer space to accept
   data for writing.

4) At least one socket in the exceptlist had an "exceptional condition"
   happen.

The return value of select is a 3-tuple of lists of sockets that are
ready for action; note that there could be more than one ready socket.
If the timeout occurred, select() returns ([], [], []) -- a 3-tuple of
empty lists.

Once you know that data is available on a socket, recv(bufsize) will
return up to bufsize bytes of data, but it might return less. Once the
end of the available data is reached, recv() will return an empty
string.

I hope this helps you understand sockets a little better.

-- 
Robin Munn
rmunn at pobox.com



More information about the Python-list mailing list