Qt信号和插槽无法正常工作

时间:2016-03-16 16:25:35

标签: qt qt5 qt5.3

当套接字在等待读取时超时时,它偶尔会失败。但是当它失败时,它会一直失败,并且尽管mpSocket的断开信号连接到slotDisconnect(),但slotDisconnected中的日志消息永远不会被报告。好像slotConnected中的return语句没有被点击,它在一个连续的循环中循环。

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

信号/插槽连接如下:

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

任何人都知道发生了什么?非常感谢

1 个答案:

答案 0 :(得分:3)

要与服务器断开连接,请使用mpSocket->disconnectFromHost();而不是mpSocket->disconnect();

实际上mpSocket->disconnect();会断开对象mpSocket的所有信号/广告位。