所以我这里有一个QTcpServer(Qt&#39的财富服务器示例的简化版)。它早先工作得很好。然后我移动了一些东西并改变了一些代码。现在我的服务器在启动时崩溃了。
之后,据我所知tcpSocket = tcpServer->nextPendingConnection();
tcpSocket仍为 NULL 。因此,所有调用如 tcpSocket-> anyCall()都会导致seg错误。应用程序输出显示:
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();
}
答案 0 :(得分:3)
要使用nextPendingConnection,您需要进行连接。因此,您有两种方式:
连接信号newConnection():
...
connect(tcpServer, &QTcpServer::newConnection, this, &Server::OnNewConnection);
...
void Server::OnNewConnection() {
if (tcpServer->hasPendingConnections()) {
tcpSocket = tcpServer->nextPendingConnection();
connect(tcpSocket, &QAbstractSocket::disconnected, tcpSocket, QObject::deleteLater);
}
}
或者使用阻塞调用waitForNewConnection():
if (tcpServer->waitForNewConnection()) {
if (tcpServer->hasPendingConnections()) {
tcpSocket = tcpServer->nextPendingConnection();
connect(tcpSocket, &QAbstractSocket::disconnected, tcpSocket, QObject::deleteLater);
}
}
不要忘记致电tcpServer->listen();