2

因此,我发现了许多使用 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()

到目前为止,这大致是我所拥有的,我在球场上吗?

4

1 回答 1

1

您为客户端和服务器使用相同的工厂。这意味着当数据从客户端连接到达您的服务器或您的客户端连接从您连接的远程服务器到达时,您将很难做正确的事情。它们都将交付给由同一个工厂实例创建的同一种协议。您将如何决定如何处理数据?

我建议使用两个不同的工厂,可能还有两个不同的协议。

接下来,这些行没有实现您想要的行为:

def lineReceived(self, line):
    self.sendline(self.factory.tb.runAlgo(line))

这接受从连接的远程端接收到的数据,将其传递给runAlgo,然后将结果发送runAlgo回连接的远程端。它不会将其传递给其他连接。您可以告诉它是同一个连接,因为self被传递给lineReceived,告诉您接收到的线路是哪个协议实例(以及哪个连接)。然后代码使用相同self的方式发送一行 - 将其发送回同一个连接。如果要将其发送到不同的连接,则需要调用sendLine不同的协议实例。

于 2013-05-29T11:20:02.983 回答