gpt4 book ai didi

c++ - 连接(在 QT 项目中)不起作用

转载 作者:行者123 更新时间:2023-11-30 04:27:44 24 4
gpt4 key购买 nike

我开始使用 QT 库创建我的第一个多线程应用程序。

根据有关 QTcpServer 和 QTcpSocket 的 qt 指南,我编写了一个服务器应用程序,它使用此构造函数创建连接:

Connection::Connection(QObject *parent) : QTcpServer(parent)
{
server = new QTcpServer();
QString ipAddress;

if (ipAddress.isEmpty())
ipAddress = QHostAddress(QHostAddress::LocalHost).toString();

if (!server->listen(QHostAddress(ipAddress),41500))
{
qDebug() << "Enable to start server";
server->close();
return;
}

connect(server,SIGNAL(newConnection()),this,SLOT(incomingConnection()));
}

这是 incomingConnection() 函数,它在每次新客户端尝试连接时创建一个新线程:

void Connection::incomingConnection()
{
QTcpSocket *socket = new QTcpSocket();
socket = this->nextPendingConnection();

MyThreadClass *thread = new MyThreadClass(socket, server);
qDebug() << "connection required by client";
if (thread != 0)
{
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
else
qDebug() << "Error: Could not create server thread.";
}

现在,这是 MyThreadClass:

MyThreadClass::MyThreadClass(QTcpSocket *socket, QTcpServer *parent) : QThread(parent)
{
tcpSocket = new QTcpSocket();
database = new Db();
blockSize = 0;

tcpSocket = socket;

qDebug() << "creating new thread";
}


MyThreadClass::~MyThreadClass()
{
database->~Db();
}


void MyThreadClass::run()
{
qDebug() << "Thread created";
connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(dataAvailable()));
exec();
}


void MyThreadClass::dataAvailable()
{
qDebug() << "data available";
QDataStream in(tcpSocket);
in.setVersion(QDataStream::Qt_4_0);

if (blockSize == 0) {
if (tcpSocket->bytesAvailable() < (int)sizeof(qint16))
return;
in >> blockSize;
}

if (tcpSocket->bytesAvailable() < blockSize)
return;

QString string;
in >> string;

//[...]

}

代码编译正常,但是当我启动客户端时(在启动服务器之后),我收到服务器的以下错误:

QObject::connect: Cannot connect (null)::readyRead() to QThread::dataAvailable()

那么服务器就无法接收到客户端的数据。

有人知道吗?

提前致谢丹妮尔

最佳答案

socket = this->nextPendingConnection();

应该是:

socket = server->nextPendingConnection();

因为您正在使用 server 成员而不是 this 作为事件的 QTcpServer,类 Connection 应该甚至继承自 QTcpServer,但仅继承自 QObject

此外,您滥用了 QThread。你应该阅读 Signals and slots across threads ,可能还有 Threads and the SQL Module , 如果 Db 正在使用 QtSql 模块。

关于c++ - 连接(在 QT 项目中)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10709178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com