我开始使用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()
然后服务器无法通过客户端接收数据。
有没有人有任何想法?
提前谢谢 丹尼尔答案 0 :(得分:2)
socket = this->nextPendingConnection();
应该是:
socket = server->nextPendingConnection();
因为您使用server
成员而不是this
作为有效QTcpServer
,所以类Connection
甚至不应继承QTcpServer
,但仅来自QObject
。
此外,您正在滥用QThread
。如果Db
正在使用QtSql模块,您应该阅读Signals and slots across threads,可能还有Threads and the SQL Module。