[Twisted-Python] UDP with multiple connections

glyph at divmod.com glyph at divmod.com
Thu Oct 11 16:27:49 EDT 2007


On 08:04 pm, radix at twistedmatrix.com wrote:
>On 10/11/07, Simon Pickles <sipickles at hotmail.com> wrote:
>>My problem is my app needs to be a server to many clients (thru TCP -
>>twisted.protocols.basic) but a client to a further server, to which it
>>passes occasional information.
>>
>>Is this possible through twisted, since I need two threads, one with 
>>the
>>server reactor.run() and one with the client connection listenTCP()?
>
>No you don't!
>
>listenTCP does not block. You can have as many connections as you want
>in a single reactor. Twisted is an *asynchronous* networking
>framework. You don't need multiple threads for this use case.

Please allow me to emphasize.  This is an important point.

Call listenTCP.  Then, immediately call listenUDP.  Then you will have a 
TCP server and a UDP server.  When TCP connections arrive, they will be 
connected using buildProtocol on your factory.  When UDP packets arrive, 
they will be delivered to datagramReceived on your UDP protocol.  You 
can then deliver those packets to whatever code you need to, whether 
it's C++ or Python or whatever.  You do not need, and should not want, 
threads for multiple sources of I/O.  If you want to take advantage of 
multiple cores or something, you can always run your C++ code that 
responds to some events in a separate process (or thread, if you are so 
inclined).

I would, however, suggest that you implement _all_ your messages using 
TCP over a single connection at first.  Once you have really understood 
and internalized the event-driven nature of Twisted, and implemented all 
the code needed to respond to position updates and so on, you will be 
able to easily split out the code that receives and parses those updates 
into a separate UDP class.  This will force you to deal with the fact 
that there is no deep architectural difference between delivering some 
messages over TCP and others over UDP.  If you instead start off with a 
two-protocol design that you do not entirely understand, your game's 
network architecture will be the result of a series of 
misunderstandings, not a well-planned whole.

Using UDP for position updates is simply an optimization, and one that 
you can make fairly late in development.  All the code to process and 
respond to them *should* be unchanged, regardless of how they are 
delivered.  Testing on local networks and fast links should be 
unaffected at first: UDP's performance advantage only comes into play 
when packets are being dropped, so it's only going to affect your game 
over long-haul links or really slow local networks.




More information about the Twisted-Python mailing list