Python asyncore with UDP

2019-07-07 19:20发布

问题:

Can I write an UDP client/server application in asyncore? I have already written one using TCP. My desire is to integrate it with support for UDP.

My question was not previously asked/answered by the following: Python asyncore UDP server

回答1:

Yes you can. Here is a simple example:

class AsyncoreSocketUDP(asyncore.dispatcher):

  def __init__(self, port=0):
    asyncore.dispatcher.__init__(self)
    self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
    self.bind(('', port))

  # This is called every time there is something to read
  def handle_read(self):
    data, addr = self.recvfrom(2048)
    # ... do something here, eg self.sendto(data, (addr, port))

  def writable(self): 
    return False # don't want write notifies

That should be enough to get you started. Have a look inside the asyncore module for more ideas.

Minor note: asyncore.dispatcher sets the socket as non blocking. If you want to write a lot of data quickly to the socket without causing errors you'll have to do some application-dependent buffering ala asyncore.dispatcher_with_send.

Thanks to the (slightly inaccurate) code here for getting me started: https://www.panda3d.org/forums/viewtopic.php?t=9364



回答2:

After long search the answer is no. Asyncore assumes the underlying socket is connection-oriented, i.e. TCP.