socket function that loops AND returns something

exarkun at divmod.com exarkun at divmod.com
Wed Sep 15 23:59:54 EDT 2004


On Wed, 15 Sep 2004 22:26:02 -0400, Brad Tilley <bradtilley at usa.net> 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?

  Threads and processes have been suggested by others.  Here's another way to do it:

    from twisted.internet import reactor, protocol

    class PrinterProtocol(protocol.Protocol):
        def connectionMade(self):
            addr = self.transport.getHost()
            print ("Client", addr.host, 
                   "connected and was directed to port", addr.port)

        def dataReceived(self, data):
            print "Client sent this message:", data
            self.transport.loseConnection()

    def listen(ip_param, port_param):
        f = protocol.ServerFactory()
        f.protocol = PrinterProtocol
        reactor.listenTCP(port_param, f, interface=ip_param)
        print "Waiting for new connections..."
        reactor.run()

  For more information, check out http://www.twistedmatrix.com/

  Jp



More information about the Python-list mailing list