La connessione (in un progetto Qt) non funziona
-
13-12-2019 - |
Domanda
Sto iniziando a creare la mia prima applicazione multithread, utilizzando le librerie Qt.
Seguendo la Guida QT su QTCPServer e QTCPSocket, ho scritto un'applicazione server che crea la connessione con questo costruttore:
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()));
}
.
Questa è la funzione IncomingConnection () che crea una nuova filettatura ogni volta che un nuovo client tenta di connettersi:
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.";
}
.
Ora, questo è 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;
//[...]
}
.
Il codice compila bene ma quando avvio un client (dopo aver avviato il server), ricevo il seguente errore da parte del server:
QObject::connect: Cannot connect (null)::readyRead() to QThread::dataAvailable()
.
Quindi il server non può ricevere dati da parte del client.
Qualcuno ha qualche idea?
Grazie in anticipo Daniele
Soluzione
socket = this->nextPendingConnection();
.
dovrebbe essere:
socket = server->nextPendingConnection();
.
Poiché si sta utilizzando il membro server
e non generanodicetagcode come this
attivo, la classe QTcpServer
non deve nemmeno ereditare da Connection
, ma solo da QTcpServer
.
Inoltre, stai male abusando QObject
.Dovresti leggere segnali e slot attraverso i fili e probabilmente Threads e il modulo SQL , se QThread
utilizza ilModulo QTSQL.