Edgarth Edgarth - 8 months ago 47
C++ Question

Can't set timeout for Qt's waitForConnected

I'm trying to make connection timeout in my Qt application customisable, but no matter what number I pass as argument to waitForConnected, the timeout is the same (and it's around 3 seconds, not the default 30).


...do stuff...
...do else stuff...

No matter what number I set koko to, the timeout keeps being around 3 seconds. What am I doing wrong?

My socket connection:

socket = new QTcpSocket();


QHostAddress addres, quint16 port

and koko im gaining from QLineEdit like that (Timeout is QLineEdit):

int koko = ui->Timeout->text().toInt()*1000;

Answer Source

From the Qt documentation for QAbstractSocket:

Waits until the socket is connected, up to msecs milliseconds. If the connection has been established, this function returns true; otherwise it returns false.

You said the method returns false after about 3 seconds. It could be a normal behaviour. See this code:

#include <QTcpSocket>
#include <QTime>

int main(int, char *) {
    QStringList hosts;
    hosts << "" << "" << "";
    for(QString host : hosts) {
        QTime timer;

        QTcpSocket socket;
        socket.connectToHost(host, 80);
        if(socket.waitForConnected(30000)) {
            qDebug() << host << "-- Connected in" << timer.elapsed();
        } else {
            qDebug() << host << "-- NOT Connected in" << timer.elapsed();;

The result is:

"" -- NOT Connected in 1
"" -- NOT Connected in 5997 
"" -- NOT Connected in 30020

In all cases, the waitForConnected() method returns false.

  • Firstly, the address ( is reachable but the port is closed: the connection fails immediately.
  • Then, The address exists (on the same network), but it take a bit more time to detect that the port is closed. It fails after 6 sec (about)
  • Finally, isn't reachable, so the full timeout is necessary to ensure the connection has failed.

Please keep in mind another important information (still from the Qt documentation):

Note: This function may fail randomly on Windows. Consider using the event loop and the connected() signal if your software will run on Windows.

It can also be your issue. Do you run on Windows?