问题描述
在 recv()
's 手册页中,我发现在这种情况下返回值可以为零:
各种域中的数据报套接字(例如,UNIX 和 Internet 域)允许零长度数据报。当这样的数据报是 收到,返回值为0。
何时或为什么应该在 UNIX 套接字互通中使用零长度数据报?它的目的是什么?
解决方法
当您希望关闭 UDP 服务线程时,此类用途之一是解除对 recvfrom() 调用的阻塞 - 设置“终止”标志并在本地主机堆栈上发送零长度数据报。
,我昨天在研究另一个问题的答案时偶然发现的一个例子。
在用于获取远程服务器当前时间的旧 RFC 868 协议中,使用 UDP 的工作流程如下所示:
When used via UDP the time service works as follows:
S: Listen on port 37 (45 octal).
U: Send an empty datagram to port 37.
S: Receive the empty datagram.
S: Send a datagram containing the time as a 32 bit binary number.
U: Receive the time datagram.
The server listens for a datagram on port 37. When a datagram
arrives,the server returns a datagram containing the 32-bit time
value. If the server is unable to determine the time at its site,it
should discard the arriving datagram and make no reply.
在这种情况下,由于 UDP 的无连接特性(TCP 版本只需要连接到服务器)。该数据报的内容将被忽略,因此不妨指定它应该为空。