使用Twisted创建客户端/服务器

6

我正在尝试使用Twisted创建客户端/服务器。 我想创建一个守护进程,该进程将作为客户端连接到另一个服务器,并作为其他客户端的服务器。 我已经编写了以下代码来描述我的问题:

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

如您所见,我想发送一些作为客户端接收到的数据(作为服务器)。我的问题当然是我的ServerControl未在ClientControl中实例化,因此我无法访问传输所需的transport以向客户端发送数据。

1个回答

3

嗨,谢谢你的回答。我会尝试这个方法。看起来这是一个好的解决方案。 - tirlototo
非常感谢您的帮助,它非常好用!祝您有美好的一天 =) - tirlototo
啊哈,你是一个扭曲的开发者;=) - tirlototo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接