问题描述
如果是这样,在什么条件下?或者,换一种说法,在 twisted 中运行这段代码是否安全:
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)
推荐答案
是的,奇怪的是,UDP 套接字可以阻塞.
Yes, oddly, a UDP socket can block.
发生这种情况的条件基本上是,某处的某些缓冲区已满,您的操作系统决定是时候阻止某些东西了.这些可以说是内核错误,但我到处都看到过它们.有时在晦涩难懂、无法重现的条件下,您绝对可以得到 EWOULDBLOCK
.
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.
为什么要在 Twisted 中执行此操作,而不是使用 Twisted 的内置 UDP 支持 虽然?
Why would you want to do this in Twisted instead of using Twisted's built-in UDP support though?
这篇关于写入 UDP 套接字会阻塞吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!