Python UDP套接字.recv()在Windows 10上停止接收



我有一个用运行在Windows 10上的python编写的udp客户端函数。我知道这不是生产质量代码,但我只是想掌握的基本原理

client = socket(AF_INET, SOCK_DGRAM)
client.bind(('192.168.0.107', CLIENT_PORT))
client.setblocking(False)
while True:
try:
data = client.recv( 1024 )
except:
continue
if data is not None:
print(data.decode('utf-8'))

我有一个运行在嵌入式设备上的服务器,定期发送小的udp数据包(udp有效负载大小为22(。这个客户端得到大约10个这样的数据包,给或拿几个,然后脚本停止接收udp数据包。try/catch块中引发的唯一异常是没有要接收的数据。如果我改为阻止行为也是一样的。

[WinError 10035] A non-blocking socket operation could not be completed immediately

服务器仍在发送数据包,我可以在Wireshark中看到它们,其中包含预期的IP地址、端口和已验证的校验和。

问题是,如果我在接收停止后添加一个发送,问题就会完全消失,我可以继续接收udp有效载荷

client = socket(AF_INET, SOCK_DGRAM)
client.bind(('192.168.0.107', CLIENT_PORT))
client.setblocking(False)
while True:
try:
data = client.recv( 1024 )
except:
continue
if data is not None:
print(data.decode('utf-8'))
client.sendto("a_udp_payload".encode('utf-8'), ('192.168.0.108' , SERVER_PORT))

我在这里遗漏了一些基本的东西吗?为什么停止处理第一个片段而不处理第二个片段?是否存在缓冲区冲洗问题?

非常感谢

尝试为套接字client.settimeout(2)设置超时

最新更新