小编典典

如何编写也是客户端的扭曲服务器?

python

如何创建也是客户端的扭曲服务器?我希望反应堆在监听的同时,也可以用于连接到也可以连接和监听的同一服务器实例。


阅读 212

收藏
2020-12-20

共1个答案

小编典典

致电reactor.listenTCPreactor.connectTCP。您可以根据需要拥有多种连接类型-服务器或客户端。

例如:

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

class SomeServerProtocol(basic.LineReceiver):
    def lineReceived(self, line):
        host, port = line.split()
        port = int(port)
        factory = protocol.ClientFactory()
        factory.protocol = SomeClientProtocol
        reactor.connectTCP(host, port, factory)

class SomeClientProtocol(basic.LineReceiver):
    def connectionMade(self):
        self.sendLine("Hello!")
        self.transport.loseConnection()

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

    log.startLogging(sys.stdout)
    factory = protocol.ServerFactory()
    factory.protocol = SomeServerProtocol
    reactor.listenTCP(12345, factory)
    reactor.run()

if __name__ == '__main__':
    main()
2020-12-20