[Twisted-Python] robust listenUDP with N clients?

marc bohlen marcbohlen at acm.org
Mon Dec 4 10:28:57 EST 2006

hi folks

I am new to twisted and new to server programming. Nonetheless, I would 
like to build a robust client-server looping mechanism in which a server 
would listen for input from N clients, say 10, and react immediately 
when it receives data from them. I have a sample (see below) that 
appears to run well, but am not sure if it will scale under real network 
load and larger N.
(I am parsing the input data received from the clients and using it to 
calculate a fibonnaci series, just for testing. The reactor can be 
stopped with keyboard input (I am on a win32 platform)).

If you see any problems with this approach, please let me know !
Thanks, marc


import os, sys, time, msvcrt
from twisted.internet import reactor, defer, task
from twisted.internet.protocol import DatagramProtocol
ports = [1007, 2007, 3007, 4007, 5007, 6007, 7007, 8007, 9007]
def check_keyboard(result):
           result = "hit"
   except:         pass

   return result
def mstop(result):
   if(result == "hit"):
       print "got hit - closing task and reactor"
def print_time(result):
   print time.asctime(time.localtime())
def fibonnaci(limit):
   first, new, second = 0,0,1
   for i in xrange(limit - 1):
       new = first + second
       first = second
       second = new
   return new
def mrun():
   d = defer.Deferred()
class server(DatagramProtocol):
   def datagramReceived(self, data, (host, port)):
       print "server received: %r from %s:%d" % (data, host, port)
       self.transport.write(data, (host, port))
       limit = int(data.split(": ")[1])
       num = fibonnaci(limit)
   print num

if __name__ == '__main__':
   print "listening on 9 ports - hit key to quit"
   mtask = task.LoopingCall(mrun)
   for i in range (0,(len(ports))):
       reactor.listenUDP(ports[i], server())

More information about the Twisted-Python mailing list