gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:57:47 26 4
gpt4 key购买 nike

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

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

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

任何帮助,不胜感激。干杯-丰富

最佳答案

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来区分超时和其他错误。

关于sockets - (recv()== 0)表示断开连接或超时? (套接字,Linux和Windows),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47739372/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com