Handling more than one request on a socket

Steve Holden sholden at holdenweb.com
Wed Aug 29 00:20:40 EDT 2001


"Jeff Grimmett" <grimmtoothtoo at yahoo.com> wrote in message
news:2df3d89d.0108281844.7736d5b9 at posting.google.com...
> Hi, pythonistas,
>
> I'm trying to come to grips with the issue of dealing with sockets,
> or, more precisely, a socket that can accept and process 'n' number of
> requests on a particular address.
>
> Right now I'm going the route of opening an inet streaming socket,
> binding it to the port, and listen()ing for requests. For example, for
> a telnet port:
>
>    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>    s.bind(('', 23))
>    s.listen(1)
>
> ... then ... ?  I've tried a number of approaches, but so far all I
> can get to work is a single connection at a time, and in most cases
> it's good for one recv().
>
> This is an issue I'm going to be looking at in a lot of cases, so I'd
> like to iron it out now if I can. Any suggestions on where to start?

Once your server port is bound and listening you need to make accept() calls
on it. The socket.accept() method returns a two-element tuple. The first
element is a socket you can use to communicate with the connecting client,
and the second is the client's address.

You should never make recv() calls on the server socket, that's not what
it's for. Regard an acceptoing socket, if you will, as a socket factory.
Once you have your client socket you can send and receive to your heart's
content, independent of the server socket, which will continue to listen.

Then, of course, you can make another accept() call on the server socket to
receive another connection. And so on. The argument to listen() tells the
transport layer how many queued requests it should allow before it starts
rejecting incoming connection requests. Apparently many OS's won't allow
more than five.

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list