Changes between Version 11 and Version 12 of FrequentlyAskedQuestions


Ignore:
Timestamp:
03/11/08 17:57:41 (14 years ago)
Author:
Glyph
Comment:

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

Legend:

Unmodified
Added
Removed
Modified
  • FrequentlyAskedQuestions

    v11 v12  
    7878
    7979Try [http://twistedmatrix.com/projects/core/documentation/howto/servers.html Writing Servers].
     80
     81=== How do I make Twisted talk to multiple clients / connect to multiple servers? ===
     82
     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.
     84
     85Sometimes people ask this question when they write a function that calls `connectTCP`, then `reactor.run()`.  You don't usually need to call `reactor.run()` yourself; let `twistd` do it.  If you do need to call it yourself, call it ''just once'' after your initial setup.  When `reactor.run()` exits, your program should too.
     86
     87=== How do I make input on one connection result in output on another? ===
     88
     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.
     90
     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:
     92
     93{{{
     94#!py
     95from twisted.internet.protocol import Protocol, Factory
     96from twisted.internet import reactor
     97
     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)
     106
     107class MultiEchoFactory(Factory):
     108    protocol = MultiEcho
     109    def __init__(self):
     110        self.echoers = []
     111
     112reactor.listenTCP(4321, MultiEchoFactory())
     113reactor.run()
     114}}}
    80115
    81116=== When I try to install my reactor, I get errors about a reactor already being installed. What gives? ===