[英]Create client/server with Twisted
I'm trying to create a client/server using Twisted.我正在尝试使用 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.我的问题当然是我的 ServerControl 没有在我的 ClientControl 中实例化,所以我无法访问将数据发送到客户端所需的传输。
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在 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.要处理您有两个工厂的情况,只需给一个工厂参考另一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.