如何编写一个同时也是客户端的扭曲服务器

如何编写一个同时也是客户端的扭曲服务器

本文介绍了如何编写一个同时也是客户端的扭曲服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I create a twisted server that's also a client?I want the reactor to listen while at the same time it can also be use to connect to the same server instance which can also connect and listen.

推荐答案

调用 reactor.listenTCPreactor.connectTCP.您可以根据需要拥有多种不同类型的连接 - 服务器或客户端.

Call reactor.listenTCP and reactor.connectTCP. You can have as many different kinds of connections - servers or clients - as you want.

例如:

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()

这篇关于如何编写一个同时也是客户端的扭曲服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 16:03