Changing network interface at runtime

434 views Asked by At

I am programming a small application with qt5. This application gets the reply from an API server every minute. Every thing is working fine but I ran into a bug.

While testing the application I found that if my wireless is disconnected and reconnected again the application will work fine. Also if I use my broadband connection and the connection is disconnected and reconnected again every thing works fine also. Now if I use my wireless at application startup then I disconnect the wireless and connect my broadband the program won't see the broadband connection and keeps giving me network error.

I use a single QNetworkAccessManager instance for the connection. The interesting thing is that If I created a new QNetworkAccessManager instance for each request the application will work fine. But I think there will be overhead in declaring a new instance for each request and making connections. I tried also to use clearAccessCache() before the request with no luck.

So basically I am looking for some thing to reset QNetworkAccessManager with each request. Here is a sample code of my request:

// At class construct
manager = new QNetworkAccessManager(this);
// ....
// At member function
url = new QUrl("http://www.gridstatusnow.com/status");
manager->get(QNetworkRequest(*url));
1

There are 1 answers

0
BartoszKP On BEST ANSWER

You can try to recreate the QNetworkAccessManager only if network is not accessible:

// At member function
if (manager->networkAccessible() == QNetworkAccessManager::NotAccessible)
{
    delete manager;
    manager = new QNetworkAccessManager(this);
}

The documentation explains:

By default the value of this property reflects the physical state of the device.