Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

twisted

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.

like image 853
Marconi Avatar asked Jul 18 '10 09:07

Marconi


1 Answers

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()
like image 65
Jean-Paul Calderone Avatar answered Nov 12 '22 01:11

Jean-Paul Calderone