简体   繁体   中英

C++ WinSock: How to know if receiver disconnected

I have two programs. They are connected via TCP, localhost, and running on the same machine. First is sending a message via send(), and second is receiving via recv(). When second program is terminated(I just stop running it), it doesn't call destructor to close the socket, and the socket is staying opened. Meanwhile program 1 is trying to send message, and doesn't get error(to reconnect), because message is actually being wrote in socket. How to know if program 2 is disconnected?

send() is not returning -1 if program 2 is terminated. I have tried using using WSAPOLLFD

    WSAPOLLFD pollfds[1];
    pollfds[0].fd = sockfd;
    pollfds[0].events = POLLOUT | POLLHUP | POLLERR; // Interested in write events, hang-up events, and error events

    int ready = WSAPoll(pollfds, 1, INFINITE); // Wait indefinitely until an event occurs
    if (ready == -1)
    {
        int error = WSAGetLastError();
        std::cout << "Error polling response! Error code: " << error << std::endl;
        isConnected = false;
    }

and end up getting error code: 10022 every time

Lets take an example, like you programmed your server that it sends "hello world" message to every client that connects with it, if the clients immediately disconnects after connecting still our server will try to send the "hello world" message.

Note: There is no such appropriate way to tell that the client has disconnected in the winsock API.

So, the thing we can do is:-

int iResult;

iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
        wprintf(L"send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
}

So, basically we are using a logic if there is a error with the function then we will assume the client has disconnected, for more advanced server you can use functions to see the IP Address of the client that disconnected and more advanced winsock API functions.

If you want to do this in real time then you can send packets in a loop and run checks.

I hope the answer helps: :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM