Python asyncore with UDP

岁酱吖の 提交于 2019-12-12 18:41:21

问题


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.



来源:https://stackoverflow.com/questions/34040658/python-asyncore-with-udp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!