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

时间:2017-12-10 13:34:09

标签: sockets recv setsockopt

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

DWORD to = 1200;
if (setsockopt (soc, SOL_SOCKET, SO_RCVTIMEO, (char *)&to, sizeof(to))) {
    ...
}

如果recv()然后返回零,我怎么能告诉这是链接断开或读取超时?如果不是我想读更多,如果它是discon我想采取其他行动。我意识到我可以删除t / o,然后我会知道它是discon,但我还需要定期监视读取过程的进展情况。

任何帮助非常感谢。干杯 - 丰富

1 个答案:

答案 0 :(得分:3)

来自SO_RCVTIMEO的手册页的socket部分:

...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.

recv的调用将在断开连接时返回0,或者如果收到零长度数据报,或者请求的字节数为0

recv的调用将返回-1任何错误,包括超时。您需要检查errno以区分超时与其他错误。