sockets - (recv() == 0) 表示断开连接或超时? (套接字、Linux 和 Windows)

标签 sockets recv setsockopt

我已经在阻塞套接字上设置了超时..

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/

相关文章:

java - 从网页发送数据到java套接字服务器的最快方法

c - winsock 的 recv 函数

python套接字文件读取超时?

python 3.2.3 : Socket takes longer to timeout than it should?

C-websocket-recv 读取的内容超过有效负载长度

c sockets - 没有收到所有发送的数据

networking - 添加 IPV6_V6ONLY 标志的动机是什么?

c - SO_KEEPALIVE : Set on the server socket or on a per-client basis?

c - 有没有办法减少套接字发送缓冲区大小的最小下限?

java - 通过 HTTP 建立 RMI 隧道的最佳方式