QTcpSocket重新连接到服务器而不阻塞GUI

时间:2018-10-26 10:19:17

标签: c++ multithreading qt sockets

我有一个客户端服务器应用程序,当服务器在客户端之前启动时,它的工作原理像一个超级按钮,但是由于我不知道服务器是否先启动,因此我需要客户端继续尝试连接服务器而不阻塞接口。 到目前为止,我想到的最好的事情就是进行这样的循环

void client::initConnection(){
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readMessage()));
    connect(tcpSocket, SIGNAL(connected()), this, SLOT(clientConnected()));
    connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(disconnectedFromHost()));

    while (tcpSocket->state() != QAbstractSocket::ConnectedState) {
    tcpSocket->abort();
    tcpSocket->connectToHost(address, port, QIODevice::ReadWrite);
    tcpSocket->waitForConnected(1000);
    }
}

但是如果我在主线程中调用此代码会阻塞gui(出于明显的原因),我以为我可能必须使用线程,但是似乎不太可能使用不同于原来的线程的套接字。创建于。 那么也许有一种方法可以运行这种方法而不会阻止gui并更改我的应用程序的体系结构?

1 个答案:

答案 0 :(得分:0)

您可以使用client类的QObject::startTimerQObject::timerEvent方法(看起来像是从QObject继承的):

void client::initConnection(){
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readMessage()));
    connect(tcpSocket, SIGNAL(connected()), this, SLOT(clientConnected()));
    connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(disconnectedFromHost()));

    // checkConnectionTimerId - is a member of class `client`
    checkConnectionTimerId = startTimer(1000);
}


void client::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == checkConnectionTimerId) {
        if (tcpSocket->state() != QAbstractSocket::ConnectedState) {
            tcpSocket->connectToHost(address, port, QIODevice::ReadWrite);
        }
    }
}