2

我已经从这个问题修改了 Jean-Paul Calderone 的代码,以实现两个服务器在一个线程中异步运行,第二个服务器是第一个服务器的客户端(他是代理)。这是我当前的代码:

from twisted.internet import protocol, reactor
from twisted.protocols import basic

class BaseServerProtocol(basic.LineReceiver):
    def lineReceived(self, line):
        self.sendLine("I can see that you said: %s" % (line,))
        self.transport.loseConnection()

##############################################################

class BrokerServerProtocol(basic.LineReceiver):
    def lineReceived(self, line):
        factory = protocol.ClientFactory()
        factory.protocol = BrokerClientProtocol
        reactor.connectTCP('localhost', 12345, factory)
        self.sendLine("I did connect but have nothing to return")
        # TODO: return broker client's response

class BrokerClientProtocol(basic.LineReceiver):
    def connectionMade(self):
        self.sendLine("Hello!")
        # TODO: receive the message from broker
        self.transport.loseConnection()

##############################################################

def main():
    import sys
    from twisted.python import log

    log.startLogging(sys.stdout)

    factory = protocol.ServerFactory()
    factory.protocol = BaseServerProtocol
    reactor.listenTCP(12345, factory)

    factory = protocol.ServerFactory()
    factory.protocol = BrokerServerProtocol
    reactor.listenTCP(12346, factory)

    reactor.run()

if __name__ == '__main__':
    main()

我想在这里修改的是替换这两# TODO行 - 首先,我想通过 BrokerClient 获取 BaseServer 的响应(第二个 todo),然后由 BrokerServer 获取它(它刚刚创建了 BrokerClient,第一个 todo)。任何人都可以帮忙吗?

4

0 回答 0