tags:

views:

76

answers:

1

Hello,

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.

+5  A: 

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()
Jean-Paul Calderone
um.. I don't get it how to use the same code above to connect on the listening server, can you enlighten me please?
Marconi
also, do you have any idea how I might use this in conjunction with the standardio? Say, while the server/client can accept/connect on the background I also want to be able to enter commands.
Marconi
The code above does make an outgoing connection. That's what the connectTCP in lineReceived does. How is this different from what you want? Also, to use it with stdio, just create a twisted.internet.stdio.StandardIO instance at some point. Like listenTCP and connectTCP, it's an event source you can create and have co-exist with just about any other event source from Twisted.
Jean-Paul Calderone