How can I check if a client disconnected through Winsock in C++?

后端 未结 4 1366
抹茶落季
抹茶落季 2020-12-15 23:06

How can I check if a client disconnected through Winsock in C++?

4条回答
  •  我在风中等你
    2020-12-15 23:47

    If the result of send() or recv() is SOCKET_ERROR and WSAGetLastError() returns WSAECONNRESET the client has disconnected.
    From MSDN:

    WSAECONNRESET

    Connection reset by peer.

    An existing connection was forcibly closed by the remote host. This normally results if the peer application on the remote host is suddenly stopped, the host is rebooted, the host or remote network interface is disabled, or the remote host uses a hard close (see setsockopt for more information on the SO_LINGER option on the remote socket). This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress. Operations that were in progress fail with WSAENETRESET. Subsequent operations fail with WSAECONNRESET.

    This also works with non blocking sockets.

    int r = recv(sock, NULL, 0, 0);
    if(r == SOCKET_ERROR && WSAGetLastError() == WSAECONNRESET){
        //client has disconnected!
    }
    

提交回复
热议问题