Sending data from one Protocol to another Protocol in Twisted?

前端 未结 1 736
無奈伤痛
無奈伤痛 2020-12-10 22:55

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

相关标签:
1条回答
  • 2020-12-10 23:01

    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
    
    class MultiEcho(Protocol):
        def connectionMade(self):
            self.factory.echoers.append(self)
        def dataReceived(self, data):
            for echoer in self.factory.echoers:
                echoer.transport.write(data)
        def connectionLost(self, reason):
            self.factory.echoers.remove(self)
    
    class MultiEchoFactory(Factory):
        protocol = MultiEcho
        def __init__(self):
            self.echoers = []
    
    reactor.listenTCP(4321, MultiEchoFactory())
    reactor.run()
    
    0 讨论(0)
提交回复
热议问题