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