Handling more than one request on a socket

Jeff Grimmett grimmtoothtoo at yahoo.com
Wed Aug 29 21:26:59 EDT 2001


First of all, thanks for the response. I *did* manage to sort it out
after another pot of coffee. Typical new-to-whatever mistakes piled
up.

"John Roth" <johnroth at ameritech.net> wrote in message news:<tooqoh5kr9a5bd at news.supernews.com>...

> >    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> >    s.bind(('', 23))
> >    s.listen(1)
 
> Doesn't your listen have to be in a loop? Each time it returns, the return
> from listen is a new connection socket descriptor (file descriptor). Then

The Python socket object documentation doesn't indicate that anything
is returned. Instead, a new socket paired with an address tuple is
returned for each new connection by using s.accept(). Unfortunately,
the listen method is buried in _socket.lib and I haven't downloaded
the source to that.

Admittedly, it could be an error in the docs, too.

The *problem* was that I piled up a lot of mistakes on each other. For
example, I was able to make any number of connections to the above
socket using s.accept(), but wasn't able to do much with them. I'd end
up with all three piled up on select.select()'s return list, but after
the first was handled the program would exist or whatever.

In general, what I needed to do was:

# Set up socket, bind it, and start listening for connections.
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s1.bind(('', 23))
s1.listen(1)

while 1: # Keep listening until something breaks the program

    # The program will dwell here until a connection is attempted.
    # A new socket plus an address tuple is returned when that happens
    c, addr = s1.accept()
    print 'connection accepted from address ', addr

    # This part is pretty bogus, but this is 'sandbox mode'
    # More or less, build a list of connections to listen to...
    conns.append(c)

    # ... and pass the list to select.select
    caller = select.select(conns,[],[])

    # If we're here, select() has detected a request (or more than 1)
that
    # needs handled.
    for i in caller[0]:

        # Here's my big screw up -- I wasn't handling data to
completion
        # This is a really simplistic loop but more or less represents
        # what I needed to do
        while 1:
            data = i.recv(512)
            if not data : break # Gotta get out of the loop somehow
...
            i.send(data) # Echo data back

Mind you, this is the sandbox and nowhere near usable for anything by
anyone, but the essentials of this seem to work for multiple telnet
connections.

Having cleared up the stupid human tricks, I moved on to SocketServer
anyway. It's threading mixin is best suited to what I need. Seems to
work, too! :-)

Thanks!



More information about the Python-list mailing list