且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何检查一个socket是否仍然打开?

更新时间:2023-11-25 16:08:28

如果你试图收到一个字节,你可以收到几个错误,如果你有一个非阻塞套接字,并尝试接收有效的连接,你会得到错误WSAEWOULDBLOCK。

If you try to recieve one byte, you can receieve several errors, if you were to have a non-blocking socket, and try to receieve on a valid connection, you will get the error WSAEWOULDBLOCK.

知道这个,我们可以检查一个非阻塞套接字像这样

Knowing this we can check a non blocking socket like so

bool connected(SOCKET sock)
{
     char buf;
     int err = recv(sock, &buf, 1, MSG_PEEK);
     if(err == SOCKET_ERROR)
     {
          if(WSAGetLastError() != WSAEWOULDBLOCK)
          {return false;}
     }
     return true;
}

,您可以从 recv的返回值 recv可能返回超时或其他几个错误以断开连接,i belive WSAEWOULDBLOCK是唯一可能返回的值,如果有错误但仍然连接,但您可能要仔细检查该返回值列表。另外,recv(MSG_PEEK)中使用的标志意味着,当您在检查后再去查看时,数据仍然是可读的,因此您不必担心丢失一个字节的数据。

as you can see from the return value of recv recv may return a timeout or several other errors for disconnect, i belive WSAEWOULDBLOCK is the only value it may return if there was an error but still connected, but you may want to double check that list of return values. Also the flag used in recv (MSG_PEEK) means that the data is still read-able when you go to look later after the check, so you don't need to worry about losing one byte of data.

我相信这将只适用于非阻塞套接字,因为它可能会阻塞,直到它收到数据。如果你想使用阻塞套接字你可能要设置它非阻塞与 ioctlsocket ,然后将其返回到原样。

I believe this will only work well with non-blocking sockets, as it may block until it receives data. If you want to use blocking socket you may want to set it non-block with ioctlsocket before this check, then return it to how it was.