socket function that loops AND returns something

Steve Holden sholden at holdenweb.com
Wed Sep 15 23:40:15 EDT 2004


Brad Tilley wrote:

> I have a function that starts a socket server looping continuously 
> listening for connections. It works. Clients can connect to it and send 
> data.
> 
> The problem is this: I want to get the data that the clients send out of 
> the loop but at the same time keep the loop going so it can continue 
> listening for connections. If I return, I exit the function and the loop 
> stops. How might I handle this?
> 
>  def listen(ip_param, port_param):
>     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>     while 1:
>         print "\nWaiting for new connection...\n"
>         s.listen(1)
>         conn, addr = s.accept()
>         print "Client", addr[0], "connected and was directed to port", 
> addr[1]
>         data = conn.recv(1024)
>         # I want to get 'data' out of the loop, but keep the loop going   
>         print "Client sent this message:", data
>         conn.close()

The classic solution to this problem is to create a new thread or fork a 
new process to handle each connection and have the original server 
imeediately loop to await a new connection.

This is what the threading and forking versions of the SocketServer 
classes do. Take a look at the ForkingMixIn and ThreadingMixIn classes 
of the SocketServer.py library to see how to turn your synchronous 
design into something asynchronous.

regards
  Steve



More information about the Python-list mailing list