Search code examples
pythonasynchronoustwistedtornadoreactor

How to "merge" two Python twisted applications?


I have two applications, written on twisted framework, for example one using twisted.web, and other using twisted.protocols.*, not web. How can I "merge" them in one, effectively sharing one reactor for both apps?

What are the best practices for that tasks? Actually I need to connect SIPSimpleApp and TornadoWeb. They both can use twisted reactor.


Solution

  • In a twisted application you can install more than one protocol-factory-client instance

    Twisted will handle connection for all application.

    So you can instanciate as server/client as you want and , you're right , reactor.run() must be launch only one time.

    So you can import your protocole and thant run the reactor loop . exemple based on the simpliest echo example:

    from twisted.internet import protocol, reactor
    
    class Echo(protocol.Protocol):
        def dataReceived(self, data):
            self.transport.write(data)
    
    class EchoFactory(protocol.Factory):
        def buildProtocol(self, addr):
            return Echo()
    
    class Echo2(protocol.Protocol):
        def dataReceived(self, data):
            self.transport.write(data+" From 2")
    
    class EchoFactory2(protocol.Factory):
        def buildProtocol(self, addr):
            return Echo2()
    
    reactor.listenTCP(1234, EchoFactory())
    
    reactor.listenTCP(1235, EchoFactory2())
    reactor.run()
    

    that's work

    You can also use twistd system, and the service collection, documentation here