Create Client / Server Using Twisted

I am trying to create a client / server using Twisted. I would like to create a daemon that will connect to another server as a client and act as a server for other clients. I am writing something like the one I'm thinking of, describing my problem:

server = sys.argv[1] control_port = 8001 class ControlClient(protocol.Protocol): def makeConnection(self, transport): [some code here -snip-] self.firstOrder(order, transport) def firstOrder(self, action, transport): self.t = transport self.t.write(action + "\0") def sendOrder(self, action): self.t.write(action + "\0") def dataReceived(self, data): [some code here -snip-] [HERE I WANT TO SEND DATA TO CLIENTS CONNECTED TO MY TWISTED SERVER, USING CONTROL SERVER] class ControlServer(ControlClient): def dataReceived(self, data): print "client said " + data def makeConnection(self, transport): self.t = transport self.t.write("make connection") print "make connection" def sendData(self, data): self.t.write("data") class ClientFactory(protocol.ClientFactory): protocol = ControlClient def clientConnectionFailed(self, connector, reason): print "Connection failed - goodbye!" reactor.stop() def clientConnectionLost(self, connector, reason): print "Connection lost - goodbye!" reactor.stop() class ServerFactory(protocol.ServerFactory): protocol = ControlServer def main(): c = ClientFactory() reactor.connectTCP(server, control_port, c) s = ServerFactory() reactor.listenTCP(9000, s) reactor.run() if __name__ == '__main__': main() 

As you can see, I would like to send (as a server) some received data (as a client). My problem, of course, my ServerControl is not created in my ClientControl, so I do not have access to the transport that is necessary to send data to clients.

Sorry if I don't understand, I'm new to Python, and Twisted and English are not my main language :( Feel free to ask if you are missing something!

Thanks in advance for any help =)

+6
python twisted client
source share
1 answer

The only thing you are missing is that you can save a list of your client connections and make this list available to code that tries to send data to all clients.

Here is an example of this in the Twisted FAQ: http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions#HowdoImakeinputononeconnectionresultinoutputonanother

There is only one factory in this example, but the idea is the same. To handle your case with two factories, just give the factory link to another.

+3
source share

All Articles