Twisted

  • Reactor + ThreadPool
    from twisted.internet import protocol, reactor
    from twisted.protocols import basic
    from twisted.internet import threads
    from twisted.python import threadable
    
    import time
    
    threadable.init()
    
    def doLongCalculation(self, data):
        print "Received [%s]" % data
        s = 5
        time.sleep(s)
        print "Finished after %d seconds [%s]" % (s, data)
        return self
    
    class TestProtocol(basic.LineReceiver):       
        def exit(self):
            self.transport.write("Exited!")
            self.transport.loseConnection()
    
        def lineReceived(self, data):
            d = threads.deferToThread(doLongCalculation, self, data)
            self.transport.write(data)
            d.addCallback(lambda _: self.exit())
    
    class TestFactory(protocol.ServerFactory):
        protocol = TestProtocol
    
    reactor.listenTCP(8888, TestFactory())
    reactor.suggestThreadPoolSize(30)
    reactor.run()
    
  • Twisted Plugin (Echo/twisted/plugins/echo_plugin.py)
    from zope.interface import implements
    
    from twisted.python import usage
    from twisted.plugin import IPlugin
    from twisted.application.service import IServiceMaker
    from twisted.application import internet
    from twisted.internet.protocol import Protocol, Factory
    
    class Echo(Protocol):
        def connectionMade(self):
            self.transport.write("Echo server listening...\r\n")
    
        def dataReceived(self, data):
            self.transport.write(data)
    
    class Options(usage.Options):
        optParameters = [["port", "p", 1234, "The port number to listen on."]]
    
    class EchoMaker(object):
        implements(IServiceMaker, IPlugin)
        tapname = "echo"
        description = "Twisted Echo Server"
        options = Options
        def makeService(self, options):
            factory = Factory()
            factory.protocol = Echo
            return internet.TCPServer(int(options["port"]), factory)
    
    serviceMaker = EchoMaker()
    
    PYTHONPATH=.:$PYTHONPATH twistd -n echo -p 7777