我已经在阻塞套接字上设置了超时..
DWORD to = 1200;
if (setsockopt (soc, SOL_SOCKET, SO_RCVTIMEO, (char *)&to, sizeof(to))) {
...
}
如果recv()返回零,我如何判断这是链接断开还是读取超时?如果是t/o,我想阅读更多内容,如果是discon,我想采取其他行动。我意识到我可以删除 t/o,然后我就会知道它已关闭,但我还需要定期监视读取过程的进展情况。
非常感谢任何帮助。干杯 - 丰富
最佳答案
来自 socket
手册页的 SO_RCVTIMEO
部分:
...if no data has been transferred and the time‐out has been reached,
then -1 is returned with errno set to EAGAIN or EWOULDBLOCK, or
EINPROGRESS (for connect(2)) just as if the socket was specified to
be non‐blocking.
来自 recv
的手册页:
These calls return the number of bytes received, or -1 if an error
occurred. In the event of an error, errno is set to indicate the
error.
When a stream socket peer has performed an orderly shutdown, the
return value will be 0 (the traditional "end-of-file" return).
Datagram sockets in various domains (e.g., the UNIX and Internet
domains) permit zero-length datagrams. When such a datagram is
received, the return value is 0.
The value 0 may also be returned if the requested number of bytes to
receive from a stream socket was 0.
在断开连接时,或者如果收到零长度数据报,或者请求的字节数为 0<,对
.recv
的调用将返回 0
/
对 recv
的调用将在出现任何错误(包括超时)时返回 -1
。您需要检查 errno
来区分超时和其他错误。
关于sockets - (recv() == 0) 表示断开连接或超时? (套接字、Linux 和 Windows),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47739372/