Sending data received in one Twisted factory to second factory

后端 未结 3 753
[愿得一人]
[愿得一人] 2021-01-01 02:39

I am trying to write a simple program using Twisted framework and I am struggling with resolving (or even with imaging how to write it) issue I couldnt find any relevant doc

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-01 02:57

    Factories are just objects. To pass data from one to another, you define and call methods and pass the data as parameter, or set attributes. I think this faq question will help you:

    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()
    

提交回复
热议问题