Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can writing to a UDP socket ever block?

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)
like image 254
Alex Gaynor Avatar asked Jan 24 '13 17:01

Alex Gaynor


1 Answers

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?

like image 169
Glyph Avatar answered Oct 09 '22 06:10

Glyph