socket.recvfrom() & sendto()

Grant Edwards grante at visi.com
Mon May 7 18:36:07 EDT 2001


In article <4VEJ6.39240$2U.16140998 at news2.rdc2.tx.home.com>, Ron Johnson wrote:

>> Quoth Ron Johnson <ron.l.johnson at home.com>:
>> 
>> | Can these be used by a server process that wants to simultaneous
>> | keep sockets open to multiple clients?
>> |
>> | The reason that I ask this is because, unlike with command/response
>> | client/server systems, the server must be able to send data to any
>> | client at any moment.  AIM/ICQ would be similar model, even though
>> | I am not writing a chat program.
>> 
>> Per your later clarification, not really!  A client can connect()
>> to a datagram service, but to my knowledge that makes no difference
>> on the server end.
>> 
>> Now of course recvfrom() returns the address of the sender, so
>> it's possible to deal with the incoming data in the context of a
>> history of multiple clients.  Or your server can bind another
>> address for each new client, and notify the client to use that.
>> But for features like "connection closed", you would want a TCP
>> stream.
>
>So my fundamental question is: how does select() support multiple
>non-blocking TCP sockets, when you can only bind 1 socket to a port?

The socket you bind to the port is the one that listens for
connections.  You call accept() on that one socket you bound to
the port. When a connection request arrives, the accept() call
returns a _new_ socket that's connect to the IP/port address
that sent the request.  If you call accept() again *on the same
socket you did the first time* it will wait for another request
to arrive and return another new socket connect to the new
requestor. 

Now you've got three open sockets: the first on that's doing
the listening for new conection requests and the two others
that are connected to something out on the 'net.  You do read()
and write() calls on the latter two, and accept() calls on the
former.

>I hope these don't sound like stupid questions, but as a hobbiest,
>I can't afford to buy Programming Python, 2nd Edition ($44 after 
>B&N's 20% discount) and Stevens' UNIX Network Programming, 2nd Ed 
>($68 - no discount)

There is plenty of example code.  Take a look at the TCP Server
Module (or whatever it's called).  It should be doing the
classic sequence:

s = socket()
bind(s,whatever)
listen(s)
s1 = accept(s)
s2 = accept(s)
s3 = accept(s)
...

-- 
Grant Edwards                   grante             Yow!  It's OKAY --- I'm an
                                  at               INTELLECTUAL, too.
                               visi.com            



More information about the Python-list mailing list