0

I'm using QTcpSocket for this program.

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

}

I attempt to connect to the server with ui->connectToHost(ip, port). If the connection fails, I call connectFunction() again to restart the connecting process. It should do this until the connection is successful. The problem arises when I call connectFunction(). This crashes the program, and I don't know why. Any help would be appreciated.

Nejat
  • 31,784
  • 12
  • 106
  • 138

1 Answers1

0

The problem is that you are calling connectFunction recursively and if the connection fails for many iterations, then you would encounter an stack-overflow error. One alternate solution is to have connectFunction as a slot and call it in a queued way to prevent recursion:

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

There are other possible solutions like implementing it in an asynchronous way and starting a timer which invokes connecting periodically when an error is occurred.

Nejat
  • 31,784
  • 12
  • 106
  • 138
  • How about a simple old-fashioned while loop?! – Hamish Moffatt Jun 01 '15 at 00:25
  • @HamishMoffatt a while loop blocks the event loop and makes GUI unresponsive if it is in the main thread. – Nejat Jun 01 '15 at 03:08
  • @Nejat Doesn't `waitForConnected(2000)` do the same? – thuga Jun 01 '15 at 07:14
  • @thuga You are right, that does the same. But in a synchronous manner calling with a queued connection is better than having a while loop. Because it lets other events be processed periodically. After all an asynchronous approach is better if it is running in the main thread. – Nejat Jun 01 '15 at 07:24