[Twisted-Python] Asynchronicity

Simon Pickles sipickles at hotmail.com
Sat Jun 9 11:09:29 EDT 2007


Hi,

I have managed to get a simple server going. It seems to accept multiple
connections correctly.

I am a little puzzled as to how to achieve an asynchonous application
using twisted. Twisted itself seems asynchronous, but my code is blocked
by the call:

reactor.run()

Is there anyway I can return from the reactor to run other code, like
GUI stuff, or other processing?

My code:

import GUI
from zope.interface import Interface
from twisted.internet import reactor
from twisted.protocols import basic
from twisted.internet.protocol import Protocol, Factory

class CNetwork(basic.LineReceiver):
    def connectionMade(self):
        GUI.Print("New Client: %s" % self.transport.getPeer().host)
        self.send = lambda x: self.transport.write(x+"\r\n")
##        if self.factory.server_data:
##            self.send("\r\n".join(self.factory.server_data))
##        else:
##            self.send("You are logged in")
        GUI.Print("Entering loop for client %s" %
self.transport.getPeer().host)

    def connectionLost(self, reason):
        GUI.Print( "%s has closed the connection" %
self.transport.getPeer().host )

    def dataReceived(self, data):
        data = data.strip()
        if not data:
            self.transport.loseConnection()
            return
        GUI.Print("%s says %r" % (self.transport.getPeer().host,data))
        self.transport.write("You said: %r\r\n" % data )
       ## self.factory.server_data.append(data + "~~")
        GUI.Print("Ready to receive more data")

class CNetworkFactory(Protocol):
    factory = Factory()
    factory.protocol = CNetwork
    def __init__(self, max_clients):
        self.max_clients = max_clients
        self.connected_clients = 0
        self.server_data = []

    def doStart(self):
        GUI.Print("Factory started -- server is waiting for a connection")
    def doStop(self):
        GUI.Print("Factory stopped -- server is now closed")

    def buildProtocol(self, addr):
        GUI.Print("Connection attempt....")
        return CNetwork()

def main():

    reactor.listenTCP(14500, CNetworkFactory(max_clients = 2))
    reactor.run()

if __name__ == "__main__":
    main()

##DO SOMETHING ELSE HERE!


###################################

Thanks for your help

_________________________________________________________________
The next generation of Hotmail is here! http://www.newhotmail.co.uk





More information about the Twisted-Python mailing list