[Twisted-Python] How can a tcp client connect with multi servers?

Andrew Bennetts andrew-twisted at puzzling.org
Fri Dec 2 02:52:49 EST 2005

On Fri, Dec 02, 2005 at 03:25:48PM +0800, Xu Ryan wrote:
> But when reactor.run() is called, the program lock here. and the codes
> after "reactor.run()" are not been called until reactor is stop.

Right.  You generally don't want to have any code after reactor.run().  The idea
is to react to events that occur, like receiving messages off the network.

For example, if you want to make a new connection while the reactor is running,
you do that from within an event handler.

There's some examples of this in Twisted, e.g. look at
An example of using this module would be:

    from twisted.internet import reactor
    from twisted.protocols.portforward import ProxyFactory
    reactor.listenTCP(1234, ProxyFactory('somewhere.com', 5678))

If you run that it will start listening on port 1234, and do nothing else until
you connect to that port.  As soon as a connection is established, a ProxyServer
protocol is made, and its connectionMade handler will call reactor.connectTCP to
establish a connection to somewhere.com's port 5678.

Here's another example of making new connections in response to events that
occur while the program is running.  You may find it simpler to understand,
although I haven't tested it so there may be bugs, and it has essentially no
error handling...:

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

class MessageReceiver(basic.LineReceiver):
    def lineReceived(self, line):
        # expects lines like "host.somewhere.com 1234 here's a message".
        host, port, message = line.split(' ', 2)
        sendMessage(host, port, message)

class MessageSender(protocol.Protocol):
    def __init__(self, message):
        self.message = message

    def connectionMade(self):
        # send the message
        # close the connection

def sendMessage(host, port, message):
    cc = protocol.ClientCreator(reactor, MessageSender, message)
    cc.connectTCP(host, port)

f = protocol.ServerFactory()
f.protocol = MessageReceiver
reactor.listenTCP(1234, f)

You may also want to work through the finger tutorial -- it's a bit long, but it
does cover this sort of thing.


More information about the Twisted-Python mailing list