【问题标题】:QTcpSocket gets NULL after QTcpServer::nextPendingConnection()QTcpSocket 在 QTcpServer::nextPendingConnection() 之后获得 NULL
【发布时间】:2016-05-14 04:57:30
【问题描述】:

所以我这里有一个 QTcpServer(Qt 的 Fortune Server 示例的简化版)。它之前工作正常。然后我移动了一些东西并更改了一些代码。现在我的服务器在启动时崩溃了。据我所知,之后

tcpSocket = tcpServer->nextPendingConnection();

tcpSocket 保持 NULL。因此,像 tcpSocket->anyCall() 这样的所有调用都会导致段错误。应用程序输出显示:

QObject::connect: invalid null parameter

所以我的问题是,为什么 tcpServer->nextPendingConnection() 返回 NULL 突然之间,在我移动东西之前它工作得很好?

以下是我的代码的相关部分:

#include <QtWidgets>
#include <QtNetwork>
#include "server.h"

Server::Server(QWidget *parent)
: QDialog(parent), statusLabel(new QLabel), tcpServer(Q_NULLPTR), tcpSocket(Q_NULLPTR), networkSession(0), blockSize(0), userAuthenticated(false)
{
    QNetworkConfigurationManager manager;
    QNetworkConfiguration config = manager.defaultConfiguration();
    networkSession = new QNetworkSession(config, this);
    sessionOpened();

    ...
    // GUI stuff here //
    ...

    this->read_newClient();
}

void Server::sessionOpened()
{
    tcpServer = new QTcpServer(this);

    // some if else checks here //

    tcpSocket = tcpServer->nextPendingConnection(); // problem here //
    connect(tcpSocket, &QAbstractSocket::disconnected, tcpSocket, &QObject::deleteLater); // line that crashes //
}

void Server::read_newClient()
{
    QString data;
    if (!clientSocket->waitForReadyRead())
    {
        qDebug() << "Cannot read";
        return;
    }
    data = readData();
}

【问题讨论】:

    标签: c++ qt qt-creator qtcpsocket qtcpserver


    【解决方案1】:

    要使用 nextPendingConnection,您需要传入连接。因此,您有两种方法:

    1. 连接到信号newConnection():

      ...
      connect(tcpServer, &QTcpServer::newConnection, this, &Server::OnNewConnection);
      ...
      void Server::OnNewConnection() {
          if (tcpServer->hasPendingConnections()) {
              tcpSocket = tcpServer->nextPendingConnection();
              connect(tcpSocket, &QAbstractSocket::disconnected, tcpSocket, QObject::deleteLater);
          }
      }
      
    2. 或者使用阻塞调用waitForNewConnection():

      if (tcpServer->waitForNewConnection()) {
          if (tcpServer->hasPendingConnections()) {
              tcpSocket = tcpServer->nextPendingConnection();
              connect(tcpSocket, &QAbstractSocket::disconnected, tcpSocket, QObject::deleteLater);
          }
      }
      

    别忘了拨打tcpServer-&gt;listen();

    【讨论】:

    • 感谢您的回答。顺便说一句,我不明白您的 connect 调用的最后一个参数。另外,我错过了 networkSession->open();
    • @Deedaus QTcpServer 可以独立于networkSession运行。
    • 那么整个包含 manager、config 和 networkSession 的部分都可以去掉吗?为什么他们在财富的例子中使用它?
    • @Deedaus 在 Fortune 示例中,它们还说明了使用网络配置(保存、读取)的操作。但 QTcpServer 的最小示例:pastebin.com/WCVsNCS5
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 2019-01-02
    相关资源
    最近更新 更多