0

所以我这里有一个 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();
}
4

1 回答 1

3

要使用 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->listen();

于 2016-05-14T06:09:51.977 回答