【问题标题】:C++ recv not receiving anything when NIC received dataNIC接收数据时C ++ recv未收到任何内容
【发布时间】:2020-08-29 10:59:32
【问题描述】:

我正在编写一个 C++ 服务器程序和一个 Qt 客户端程序。问题是,当 tcpdump 清楚地显示来自客户端的 tcp 数据包已传递到我的网络接口时,recv() 会一直等待。

服务器程序在 Centos 7.7 上运行并使用 g++ 4.8.5 编译

    while (true) {
        sockaddr_in client_addr{0};
        socklen_t client_len = sizeof(sockaddr_in);
        newsockfd = accept(sockfd, (sockaddr*)&client_addr, &client_len);
        cout << "New connection from " << inet_ntoa(client_addr.sin_addr) << endl;

        long bytes;
        char buf[1000];
        while (true) {
            bytes = recv(newsockfd, buf, 1000, 0);
            if (bytes < 1) {
                if (bytes < 0) { cout << "Error: " << errno << ", " << strerror(errno) << endl; }
                break;
            }
            ProcessRequest(buf, bytes);
        }

        close(newsockfd);
        cout << "Host " << inet_ntoa(client_addr.sin_addr) << " disconnected..." << endl;
    }

客户端程序在 Windows 上运行并使用 msvc 2017 和 Qt 编译:

    QTcpSocket* loginClient = new QTcpSocket(this);
    loginClient->connectToHost(ipAddr, Port);
    if (!loginClient->waitForConnected(30000)) { return; }
    char data[100] = "12345678";
    int sendLen = loginClient->write(data, 9);
    if (sendLen == -1) { return; }

服务器能够检测到来自客户端的连接,因此 IP 和端口问题已经解决。此外,服务器无法正确检测与此 Qt 客户端的断开连接。断线检测通常会延迟数分钟或无限期。

有趣的是,我写了另一个客户端程序,在另一个 Centos 上运行,服务器完美地工作。所以我假设服务器程序很好?

感谢您的帮助。

【问题讨论】:

  • loginClient->waitForBytesWritten(); loginClient->disconnectFromHost();如果您希望在没有停滞状态等的情况下进行更多套接字优化,请在此处查看我的答案 -> stackoverflow.com/questions/47268023/…

标签: c++ c qt sockets network-programming


【解决方案1】:

发现错误。原来客户端已经与服务器建立了三个连接,其中只有一个连接,两个在队列中。数据包不是从连接的套接字进入服务器的。这就是打开的文件描述符没有从 NIC 读取任何内容的原因。

【讨论】:

    猜你喜欢
    • 2012-07-05
    • 2011-05-29
    • 2012-04-23
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 2016-07-23
    相关资源
    最近更新 更多