문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top