在 Qt 中创建一个尝试连接到服务器的客户端,如果失败,它会一直尝试直到连接

Making a client in Qt that tries to connect to server, and if it fails, it keeps trying until it connects

我正在为这个程序使用 QTcpSocket

void MainWindow::connectFunction()
{

    socket->connectToHost(ip, port);
    if(socket->waitForConnected(2000))
    {   
        QTime time = QTime().currentTime();

        ui->textBrowser->append('[' + time.toString("h:m") + "] Connection successful.");
    }
    else
    {
        QTime time = QTime().currentTime();
        ui->textBrowser->append('[' + time.toString("h:m") + "] Connection failed. Retrying...");
        connectFunction();
    }

}

我尝试使用 ui->connectToHost(ip, port) 连接到服务器。如果连接失败,我会再次调用 connectFunction() 以重新启动连接过程。它应该这样做,直到连接成功。当我调用 connectFunction() 时出现问题。这会使程序崩溃,我不知道为什么。任何帮助将不胜感激。

问题是您正在递归调用 connectFunction,如果多次迭代连接失败,那么您会遇到堆栈溢出错误。另一种解决方案是将 connectFunction 作为插槽并以排队的方式调用它以防止递归:

void MainWindow::connectFunction()
{

    socket->connectToHost(ip, port);
    if(socket->waitForConnected(2000))
    {   
        QTime time = QTime().currentTime();

        ui->textBrowser->append('[' + time.toString("h:m") + "] Connection successful.");
    }
    else
    {
        QTime time = QTime().currentTime();
        ui->textBrowser->append('[' + time.toString("h:m") + "] Connection failed. Retrying...");
        QMetaObject::invokeMethod(this, "connectFunction", Qt::QueuedConnection );
    }
}

还有其他可能的解决方案,例如以异步方式实现它并启动一个计时器,该计时器在发生错误时定期调用连接。