How do I set-up Multiple socket connections

James J. Besemer jb at cascade-sys.com
Sat Sep 28 04:38:57 EDT 2002


Kat & Huw wrote:

> Ok, I want to iterate through a server IP list and establish
> multiple socket connections to the various IP address' in the list.
>  
> I can do the iterations and I can make single connections, but I can't
> work out how I can connect to several address at once.
>  
> I understand that a socket is closed, or closes after its done getting 
> the ACk or
> whatever after sending a request, but how on earth do I connect to like 5
> addresses at once?

This is a complicated problem.

Two general solutions suggest themselves.

A. You can use the select system call to wait on multiple socket I/O 
operations at once.  It waits until one is ready to proceed and it tells 
you which one(s) are ready.  Read the doc.  You would have some 
non-trivial state machine logic to go with it to translate the select 
results into the various i/o functions on individual sockets.  On Unix, 
select will multiplex socket AND regular I/O.  On Windows select only 
works for sockets.

B. You can dispatch multiple threads, one for each host you wish to 
communicate with.  Each thread would do the initial socket() and 
connect() to connect to the remote host and then send() or recv() as 
appropriate.  Then it's up to you to coordinate the results.  If there 
is no coordination to do, e.g., if the results all go to different 
files, then you can skip that part.  If you do need to coordinate 
results, e.g., to funnel all results to a single sink, the Queue class 
likely will be useful.

My preference is alternative B and I have used it successfully on a 
number of projects on Linux.  I have heard rumors that threads and 
socket I/O is problematic on some platforms but I don't know which ones.

Regards

--jb

-- 
James J. Besemer		503-280-0838 voice
2727 NE Skidmore St.		503-280-0375 fax
Portland, Oregon 97211-6557	mailto:jb at cascade-sys.com
				http://cascade-sys.com	








More information about the Python-list mailing list