UDP reading on multiple sockets

Thomas Vogel thomas.vogel at likeabird.de
Sat May 16 21:52:46 EDT 2009


Hi all,

I'm currently have the problem that I try to read UDP messages from 
multiple sockets in parallel. So let's say I get UDP packets from the 
same IP on the ports 2000, 2001, 2002,...

Therefore I created the following class.
But if I try to instantiate it several times with different ports I 
experience that if I get a broadcast message all ports are waking up, 
the 1st socket is using the message and the others close itself as the 
buffer is empty.

Does anybody have an idea how to do this in a better way?
I just need non-blocking UDP-receiver that are listening on several 
ports in parallel and return me the incomming messages. Are there 
examples in the net that describe this problem?

class Receiver(asyncore.dispatcher, threading.Thread):
     '''
     This is the command receiver entity.
     '''

     def __init__(self, api, localIp, localPort):

         asyncore.dispatcher.__init__(self)
         threading.Thread.__init__(self)
         self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
         self.bind((localIp, localPort))
         self.cv = threading.Condition()
         self.data = []
         self.sorbasApi = api

     def handle_connect(self):
         return

     def writable(self):
         return False

     def handle_error(self):
         self.logger.error('error')
         return asyncore.dispatcher.handle_error(self)

     def handle_read(self):
         s = self.recv(4096)
         self.cv.acquire()
         self.data.append(s)
         self.cv.notifyAll()
         self.cv.release()

     def handle_close(self):
         self.close()

     def run(self):
         asyncore.loop()

     def flush(self):
         self.data = []

     def readNextMsg(self, paramSet, timeout=1):
         if len(self.data) == 0:
             self.cv.acquire()
             self.cv.wait(timeout)
             self.cv.release()
         if len(self.data) > 0:
             buffer = array('B', self.data.pop(0)).tolist()
             m = ReceiveMessage(self.sorbasApi, paramSet)
             m.decode(buffer)
             return m
         else:
             return None

     def __del__(self):
         self.close()

Thanks a lot in advance
Thomas



More information about the Python-list mailing list