简体   繁体   中英

How to write a twisted server that is also a client?

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.

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

For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM