Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Why QNetworkReply do not finished immediately sometimes while network is not connected



  • I have code like this:

    bool canConnectToInternet()
    {
    		QNetworkAccessManager netManager;
    		QNetworkRequest m_request(Host);
    
    		QNetworkReply* reply = netManager.get(m_request);
    
    		QTimer timer;
    		timer.setInterval(3000);
    		timer.setSingleShot(true);
    		QEventLoop loop;
    		QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
    		QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    		timer.start();
    		loop.exec();
    		if (timer.isActive())
    		{  // not time out
    			timer.stop();
    			if (reply->error() == reply->NoError)
    			{
    				return true;
    			}
    			qDebug() << "canConnectToInternet: " << reply->error();
    		}
    		else
    		{
    			qDebug() << "canConnectToInternet: timeout";
    			QObject::disconnect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    		}
    		return false;
    }
    

    My question is that when the net is connected it work well, and i cut the net when running the program, and it will cost 3 ms then print "canConnectToInternet: timeout".But when I restart the app it immediately return.

    Thanks!



  • @Hanson said in Why QNetworkReply do not finished immediately sometimes while network is not connected:

    cost 3 ms

    Ok, define the difference between "immediately" and 3ms.


  • Moderators

    @VRonin thats your concern? And not the content of that function? 🙈



  • @VRonin I wrote it wrong.--! It cost 3 seconds.


Log in to reply