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 documentation for:
The main reactor uses two factories, one custom, listening for TCP connections on given port (say, 8000) and second one, to log into given IRC server and channel. On receiving data (simple, one line text) on the factory listening at 8000, I need to pass that data to second factory, so it could be then processed accordingly - either send a message with that text to a channel, or a priv message to some person, thats not really important now. I cant find any way to get the data from first factory and send it to another, for processing (maybe like usual received connection for second IRC factory?).
If this could be somehow resolved, then I would like to add one or even more factories (Jabber for example) to send the received data on port 8000 to all of them at once, to pass it accordingly to protocols (IRC to a channel, Jabber to a contact, and so on).
Is there anyone who met similar issue and is willing to give me some advice or even share some lines of code? Any help will be highly appreciated!
Thanks in advance.
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 itstransport.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
andconnectionLost
, 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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With