La conexión (en un QT proyecto) no funciona
-
13-12-2019 - |
Pregunta
Estoy empezando a crear mi primera aplicación multiproceso, usando las bibliotecas QT.
Tras la qt guía sobre QTcpServer y QTcpSocket, escribí una aplicación de servidor que crear la conexión con este constructor:
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()));
}
Este es el incomingConnection() función que crea un nuevo hilo cada vez que un nuevo cliente intente conectarse:
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.";
}
Ahora, esto es 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;
//[...]
}
El código se compila bien, pero cuando empiezo un cliente (después de iniciar el servidor), recibo el siguiente error de servidor:
QObject::connect: Cannot connect (null)::readyRead() to QThread::dataAvailable()
A continuación, el servidor no puede recibir datos por el cliente.
¿alguien tiene alguna idea?
gracias de antemano Daniele
Solución
socket = this->nextPendingConnection();
debe ser:
socket = server->nextPendingConnection();
porque se está utilizando el server
miembro y no this
como la activo QTcpServer
, la clase Connection
no debería heredar de QTcpServer
, pero sólo a partir de QObject
.
También, se están haciendo mal uso de QThread
.Usted debe leer Las señales y las ranuras a través de los subprocesos, y probablemente Hilos y el Módulo de SQL, si Db
es el uso de la QtSql módulo.