この質問から Jean-Paul Calderone のコードを変更して、2 つのサーバーが 1 つのスレッドで非同期に実行され、2 番目のサーバーが最初のサーバーのクライアントになるようにしました (彼はブローカーです)。これは私の現在のコードです:
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 の応答を取得し (2 番目の todo)、BrokerServer (BrokerClient を作成したばかり、最初の todo) によってそれを取得します。誰でも助けることができますか?