[Twisted-Python] two twisted clients, how can I trigger the other one's callback in one's callback?

Arnar Birgisson arnarbi at gmail.com
Thu Jun 21 05:06:47 EDT 2007


On 6/21/07, slowtech chen <slowtech.chen at yahoo.com> wrote:
> Thanks guys, It helped a lot, but still something I haven't figured out,
> what I do is like:
>
> reactor.connectTCP(host1, port1, factory1)
> reactor.connectTCP(host2, port2, factory2)
>
> using different protocols, so I can't do it the way Arnar does.

Assuming you pass data from host1 to host2, you can store a reference
to factory2 in factory1.

from twisted.internet.protocol import Protocol
from twisted.internet import reactor, protocol

class InputProtocol(Protocol):

   def connectionMade(self):
       print "Input connected"

   def connectionLost(self, reason):
       print "Input disconnected"

   def dataReceived(self, data):
       # repeat the data to all output connections
       print "relaying data"
       for conn in self.factory.output_factory.connections:
           conn.transport.write(data)

class OutputProtocol(Protocol):

    def connectionMade(self):
        print "Output connected"
        self.factory.connections.append(self)

    def connectionLost(self, reason):
        print "Output disconnected"
        self.factory.connections.remove(self)

class InputFactory(protocol.ClientFactory):
    protocol = InputProtocol

    def __init__(self, output_factory):
        self.output_factory = output_factory

class OutputFactory(protocol.ClientFactory):
   protocol = OutputProtocol

   def __init__(self):
       self.connections = []


if __name__ == '__main__':

   of = OutputFactory()
   if = InputFactory(of)
   reactor.connectTCP("sourcehost", 10001, if)
   reactor.connectTCP("destinationhost", 10002, of)
   reactor.run()


(totally untested)

Arnar




More information about the Twisted-Python mailing list