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

标签 c++ linux python-2.7 sockets twisted

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

clientConnectionLost(self, connector, reason)

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

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 相同/相似的功能?

最佳答案

来自 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;
}

关于C++ 客户端需要找出套接字被扭曲的服务器关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36982067/

相关文章:

c++ - std::mt19937 和 std::uniform_real_distribution 每次都返回边界值

c++ - 我可以用 C++ 扩展 lisp 吗?

linux - NFS 时间间隔过长

python - 遍历列表返回负索引

python - pipenv 无法在 Mac OS X 10.10.6 El Capitan 上的 Python 2.7.10 上正确安装

python - Ubuntu - 找不到适用于 python2 的 PySide 模块,但适用于 python3

使用 openCV 和 openCL 的 Android Studio 应用程序

c++ - 如何删除 Sprite 并再次使用相同的 Sprite

linux - Linux内核中virt_to_phys和CPU的MMU是什么关系?

linux - 如何创建多任务 cron 作业?