1

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

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

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

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

4

1 回答 1

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.

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

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

于 2017-12-10T13:43:33.217 回答