C++ 客户端需要找出套接字被扭曲的服务器关闭

C++ client needs to find out socket was closed by twisted server

我有一个扭曲的服务器,它做了一些事情然后关闭了连接。 python 客户理解

clientConnectionLost(self, connector, reason)

连接已关闭并且工作正常。 但是,我还有一个 C++ 客户端与同一个扭曲的服务器通信。目前似乎不明白 connection/socket 已关闭。我该如何检查?

string tcp_client::receive(int size=1024)
{
    char buffer[size];
    string reply;

    int msg = recv(sock , buffer , sizeof(buffer) , 0);

    // Receive a reply from the server
    if(msg < 0)
    {
         puts("recv failed");
         // Exit the programm
         exit(0);
    }
    reply = buffer;
    return reply;
}

是C++客户端的接收码。 如何使用 C++ 客户端实现 clientConnectionLost 的 same/similar 功能?

来自man recv

The return value will be 0 when the peer has performed an orderly shutdown.

所以在recv调用之后,你可以这样写:

string tcp_client::receive(int size=1024)
{
    char buffer[size];
    string reply;

    // Receive a reply from the server
    int msg = recv(sock , buffer , sizeof(buffer) , 0);

    if(msg < 0)
    {
         puts("recv failed");

         // Exit the programm
         exit(0);
    }
    else if (0 == msg)
    {
        // the connexion has been closed by server
        puts("Connexion lost!");

        // close the socket
        close(sock);

        // return something
        return string("");
    }
    reply = buffer;
    return reply;
}