Pergunta

I need to check the Internet Connection If I get Socket Error. I am proceeding like this,

void Client::socketError(QAbstractSocket::SocketError socketError) {
   HttpPost("https://www.google.co.in/");
}

void Client::HttpPost(QString URL ) {

    QNetworkRequest request = QNetworkRequest();
    request.setUrl(QUrl(URL));

    QNetworkAccessManager *mNetworkAccessManager = new QNetworkAccessManager(this);
    bool result = connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply*)),
                          this, SLOT(HttpResponse(QNetworkReply *)));

    mNetworkAccessManager->get(request);
    qDebug() << "::: Client.cpp  Request made to Service :::";
}

void Client::HttpResponse(QNetworkReply* reply) {

    if (reply->error() == QNetworkReply::NoError) {
        qDebug() << "\n  Internet Ok **********";
    } else {
        qDebug() << "\n No Internet **********" << reply->errorString();
        showDialog("No Inernet");
    }
}

and I am connecting to Signals and Slots like

connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
        this, SLOT(socketError(QAbstractSocket::SocketError)));

But some times I am getting "No Internet Dialog " Even If wi-fi Is Available. Why ?


Method 2:

// this method will return true If Net is available false other wise
// but even this is return false some times even Wi fi signal is Available 

bool Client::isNetworkAvailable() {
    bool isFound = false;
    QNetworkConfigurationManager netMgr;
    QList<QNetworkConfiguration> mNetList = netMgr.allConfigurations(QNetworkConfiguration::Active);

    if (mNetList.count() > 0) {
            if (netMgr.isOnline()) {
                isFound = true;
            }
    }
    qDebug() << "\n ************** isNetworkAvailable:::" << isFound;
    return isFound;
}

Is there a problem in my code?

Foi útil?

Solução

Your network check snippet seems a bit too complicated. You could simply just call the following method:

bool QNetworkConfigurationManager::isOnline () const

Returns true if the system is considered to be connected to another device via an active network interface; otherwise returns false.

If this does not work for someone, it very likely means that the internet connection is unreliably, especially if it does not work randomly.

Outras dicas

What about

NetworkAccessibility QNetworkAccessManager::networkAccessible ()

networkAccessible : NetworkAccessibility

This property holds whether the network is currently accessible via this network access manager.

If the network is not accessible the network access manager will not process any new network requests, all such requests will fail with an error. Requests with URLs with the file:// scheme will still be processed.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top