Skip to content Skip to sidebar Skip to footer

Sending Data From One Protocol To Another Protocol In Twisted?

One of my protocols is connected to a server, and with the output of that I'd like to send it to the other protocol. I need to access the 'msg' method in ClassA from ClassB but I

Solution 1:

Twisted FAQ:

How do I make input on one connection result in output on another?

This seems like it's a Twisted question, but actually it's a Python question. Each Protocol object represents one connection; you can call its transport.write to write some data to it. These are regular Python objects; you can put them into lists, dictionaries, or whatever other data structure is appropriate to your application.

As a simple example, add a list to your factory, and in your protocol's connectionMade and connectionLost, add it to and remove it from that list. Here's the Python code:

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

classMultiEcho(Protocol):
    defconnectionMade(self):
        self.factory.echoers.append(self)
    defdataReceived(self, data):
        for echoer in self.factory.echoers:
            echoer.transport.write(data)
    defconnectionLost(self, reason):
        self.factory.echoers.remove(self)

classMultiEchoFactory(Factory):
    protocol = MultiEcho
    def__init__(self):
        self.echoers = []

reactor.listenTCP(4321, MultiEchoFactory())
reactor.run()

Post a Comment for "Sending Data From One Protocol To Another Protocol In Twisted?"