Qt Signal and slots not working as expected

242 views Asked by At

When the socket times out while waiting for a read it occasionally fails. But when it does fail, it continuously fails, and the log message in slotDisconnected never gets reported despite mpSocket's disconnected signal being connected to slotDisconnect(). It's as if the return statement in slotConnected isn't being hit and it's going round in a continous loop.

void Worker::slotDisconnected()
{
    // Attempt to reconnect
    log("Disconnected from Server. Attempting to reconnect...");

    // fires mpSocket's connect signal (which is connected to slotConnected)
    connectToServer();
}

void Worker::slotConnected()
{
    // Loop forever while connected and receiving messages correctly
    while(1)
    {

        if(mpSocket->bytesAvailable())
        {
            // A message is ready to read
        }
        else if(!mpSocket->waitForReadyRead(mSocketTimeOut))
        {
            // waitForReadyRead returned false - instead of continuing and trying again, we must disconnect as sometimes
            // (for some unknown reason) it gets stuck in an infinite loop without disconnecting itself as it should
            log("Socket timed out while waiting for next message.\nError String: " + mpSocket->errorString());
            msleep(3000);
            mpSocket->disconnect();
            return;
        }
    }
}

The signals/slots are connected like so:

connect(mpSocket, &QAbstractSocket::disconnected, this, &TRNGrabberWorker::slotDisconnected);
connect(mpSocket, &QAbstractSocket::connected, this, &TRNGrabberWorker::slotConnected);

Anyone have any idea's what's going on? Would be much appreciated

1

There are 1 answers

2
Evgeny S. On

To disconnect from server use mpSocket->disconnectFromHost(); instead of mpSocket->disconnect();.

Actually mpSocket->disconnect(); disconnects all signals/slots of object mpSocket.