The connect (in a QT project) doesn't work

2k views Asked by At

I'm starting to create my first multithread application, using the QT libraries.

Following the qt guide about QTcpServer and QTcpSocket, i wrote a server application that create the connection with this 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()));
}

This is the incomingConnection() function which create a new thread everytime a new client try to connect:

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.";
}

Now, this is 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;

    //[...]

 }

The code compiles fine but when i start a client (after starting the server), i receive the following error by server:

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

Then the server cannot receive data by the client.

does anyone have any idea?

thanks in advance Daniele

1

There are 1 answers

3
alexisdm On BEST ANSWER
socket = this->nextPendingConnection();

should be:

socket = server->nextPendingConnection();

because you are using the server member and not this as the active QTcpServer, the class Connection shouldn't even inherit from QTcpServer, but only from QObject.

Also, you are misusing QThread. You should read Signals and slots across threads, and probably Threads and the SQL Module, if Db is using the QtSql module.