Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create client/server with Twisted

I'm trying to create a client/server using Twisted. I'd like to create a daemon, which will be connected to another server as a client and act as a server for other clients. I've writen something like that which I think describes 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'd like to send (as a server) some data received (as a client). My problem is of course my ServerControl is not instantiated in my ClientControl so I don't have access to transport which is required to send data to clients.

like image 631
tirlototo Avatar asked Mar 28 '11 13:03

tirlototo


1 Answers

The only thing you seem to be missing is that you can keep a list of your client connections and make that list available to the code that's trying to send out data to all the clients.

There's an example of this in the Twisted FAQ: http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions#HowdoImakeinputononeconnectionresultinoutputonanother

That example only has one factory, but the idea is the same. To handle your case with two factories, just give one factory a reference to the other.

like image 94
Jean-Paul Calderone Avatar answered Oct 25 '22 17:10

Jean-Paul Calderone