Edgarth Edgarth - 10 days ago 5
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).

Example:

if(socket->waitForConnected(koko))
{
...do stuff...
}
else
{
...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();
socket->connectToHost(addres,port);


where:

QHostAddress addres, quint16 port


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

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

Answer

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 << "127.0.0.1" << "10.1.25.62" << "192.168.1.0";
    for(QString host : hosts) {
        QTime timer;
        timer.start();

        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:

"127.0.0.1" -- NOT Connected in 1
"10.1.25.62" -- NOT Connected in 5997 
"192.168.1.0" -- NOT Connected in 30020

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

  • Firstly, the address (127.0.0.1) 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, 192.168.1.0 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?

Comments