Changes between Version 11 and Version 12 of FrequentlyAskedQuestions

03/11/08 17:57:41 (14 years ago)

Add some "I don't quite know Python" FAQs.


  • FrequentlyAskedQuestions

    v11 v12  
    7979Try [ Writing Servers].
     81=== How do I make Twisted talk to multiple clients / connect to multiple servers? ===
     83Twisted already does this.  If you want to connect to multiple servers, call `connectTCP` (or similar) multiple times, and each call will result in a single outgoing connection.  `listenTCP` will result in your factory (and therefore your protocol) being invoked for each incoming connection.
     85Sometimes people ask this question when they write a function that calls `connectTCP`, then ``.  You don't usually need to call `` yourself; let `twistd` do it.  If you do need to call it yourself, call it ''just once'' after your initial setup.  When `` exits, your program should too.
     87=== How do I make input on one connection result in output on another? ===
     89This seems like it's a Twisted question, but actually it's a Python question.  Each `Protocol` object represents one connection; you can call its `transport.write` to write some data to it.  These are regular Python objects; you can put them into lists, dictionaries, or whatever other data structure is appropriate to your application.
     91As a simple example, add a list to your factory, and in your protocol's `connectionMade` and `connectionLost`, add it and remove it to that list.  Here's the Python code:
     95from twisted.internet.protocol import Protocol, Factory
     96from twisted.internet import reactor
     98class MultiEcho(Protocol):
     99    def connectionMade(self):
     100        self.factory.echoers.append(self)
     101    def dataReceived(self, data):
     102        for echoer in self.factory.echoers:
     103            echoer.transport.write(data)
     104    def connectionLost(self, reason):
     105        self.factory.echoers.remove(self)
     107class MultiEchoFactory(Factory):
     108    protocol = MultiEcho
     109    def __init__(self):
     110        self.echoers = []
     112reactor.listenTCP(4321, MultiEchoFactory())
    81116=== When I try to install my reactor, I get errors about a reactor already being installed. What gives? ===