QTcpSocket在不阻塞GUI的情况下重新连接到服务器

QTcpSocket reconnect to server without blocking GUI

本文关键字:情况下 重新连接 服务器 GUI QTcpSocket      更新时间:2023-10-16

我有一个客户端-服务器应用程序,当服务器先于客户端启动时,它就像一个魅力,但由于我不知道服务器是否首先启动,我需要客户端继续尝试连接到服务器,而不阻塞接口。到目前为止,我想到的最好的事情是做一个像这样的循环

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和更改应用程序架构的情况下运行这种方法?

您可以使用client类(看起来像是从QObject继承的(的QObject::startTimer和QOobject::timerEvent方法,如下所示:

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