A conexão (em um projeto QT) não funciona
-
13-12-2019 - |
Pergunta
Estou começando a criar minha primeira aplicação multithread, utilizando as bibliotecas QT.
Seguindo o guia qt sobre QTcpServer e QTcpSocket, escrevi um aplicativo de servidor que cria a conexão com este construtor:
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()));
}
Esta é a função incomingConnection() que cria um novo thread toda vez que um novo cliente tenta se conectar:
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.";
}
Agora, esta é 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;
//[...]
}
O código compila bem, mas quando inicio um cliente (após iniciar o servidor), recebo o seguinte erro por servidor:
QObject::connect: Cannot connect (null)::readyRead() to QThread::dataAvailable()
Então o servidor não poderá receber dados do cliente.
alguém tem alguma ideia?
Obrigado antecipadamente Daniele
Solução
socket = this->nextPendingConnection();
deveria estar:
socket = server->nextPendingConnection();
porque você está usando o server
membro e não this
como o ativo QTcpServer
, a classe Connection
nem deveria herdar de QTcpServer
, mas apenas a partir QObject
.
Além disso, você está usando mal QThread
.Você deveria ler Sinais e slots entre threads, e provavelmente Threads e o Módulo SQL, se Db
está usando o módulo QtSql.