简体   繁体   English

C++ WinSock:如何知道接收器是否断开连接

[英]C++ WinSock: How to know if receiver disconnected

I have two programs.我有两个程序。 They are connected via TCP, localhost, and running on the same machine.它们通过本地主机 TCP 连接,并在同一台机器上运行。 First is sending a message via send(), and second is receiving via recv().首先是通过 send() 发送消息,其次是通过 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.同时程序 1 正在尝试发送消息,并且没有收到错误(重新连接),因为消息实际上是在套接字中写入的。 How to know if program 2 is disconnected?如何知道程序 2 是否断开连接?

send() is not returning -1 if program 2 is terminated.如果程序 2 终止,send() 不会返回 -1。 I have tried using using WSAPOLLFD我试过使用 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并最终每次都收到错误代码:10022

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.让我们举个例子,就像你对你的服务器进行编程,它向每个连接它的客户端发送“hello world”消息,如果客户端在连接后立即断开连接,我们的服务器仍然会尝试发送“hello world”消息。

Note: There is no such appropriate way to tell that the client has disconnected in the winsock API.注意:在 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.所以,基本上我们使用的逻辑是,如果 function 出现错误,那么我们将假设客户端已断开连接,对于更高级的服务器,您可以使用函数查看断开连接的客户端的 IP 地址和更高级的 winsock API 函数。

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: :)我希望答案有所帮助::)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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