因此,我发现了许多使用 Twisted 创建多个同时客户端连接的示例,以及如何支持多种协议以及如何遍历多个客户端(http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions#HowdoImakeinputononeconnectionresultinoutputonanother),但我正在寻找的是一个代码片段,它演示了如何从侦听器套接字读取数据,进行一些操作,并通过客户端套接字将其写出。
我知道我已经接近了,我只是还没有确定模式。
为了清楚起见,我想从端口 9000 读取一行 -> 传递给工厂 -> 运行算法 -> 将端口 9001 写出到另一个进程。
class ClientSideProtocol(basic.LineReceiver):
def __init__(self, factory):
self.factory = factory
def connectionMade(self):
print "Made Connection to JoaC"
def connectionLost(self, reason):
print "Lost Connection to JoaC"
def lineReceived(self, line):
self.sendline(self.factory.tb.runAlgo(line))
class EmulatorFactory(protocol.ClientFactory):
def __init__(self, sensorName):
self.tb = tbg2(sensorName)
def startedConnecting(self,connector):
print "Started to connect."
def buildProtocol(self, addr):
print "buildProtocol called"
return ClientSideProtocol(self)
def clientConnectionLost(self, connector, reason):
print 'Lost connection. Reason:', reason
def clientConnectionFailed(self, connector, reason):
print 'Connection failed. Reason:', reason
def main():
sensorName = "Test1"
mystuff = EmulatorFactory(sensorName)
reactor.listenTCP(9000, mystuff)
reactor.connectTCP(host = "localhost", port = 9001, factory = mystuff, timeout = 5)
reactor.run()
到目前为止,这大致是我所拥有的,我在球场上吗?