Can writing to a UDP socket ever block?

三世轮回 提交于 2019-12-05 15:03:54

问题


And if so, under what conditions? Or, phrased alternately, is it safe to run this code inside of twisted:

class StatsdClient(AbstractStatsdClient):
  def __init__(self, host, port):
    super(StatsdClient, self).__init__()
    self.addr = (host, port)
    self.server_hostname = socket.gethostname()
    self.udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

  def incr(self, stat, amount=1):
    data = {"%s|c" % stat: amount}
    self._send(data)

  def _send(self, data):
    for stat, value in data.iteritems():
      self.udp_sock.sendto("servers.%s.%s:%s" % (self.server_hostname, stat, value), self.addr)

回答1:


Yes, oddly, a UDP socket can block.

The conditions under which this can happen are basically, some buffers somewhere fill up, your operating system decides it's time for something to block. These are arguably kernel bugs, but I've seen them here and there. You can definitely get EWOULDBLOCK sometimes under obscure, impossible-to-reproduce conditions.

Why would you want to do this in Twisted instead of using Twisted's built-in UDP support though?




回答2:


It could fail if your network interface goes down, for example:

[ENETDOWN] The local network interface used to reach the destination is down.



来源:https://stackoverflow.com/questions/14507028/can-writing-to-a-udp-socket-ever-block

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