使用QNetworkAccessManager和QNetworkReply进行超时处理

时间:2016-11-16 17:03:08

标签: qt connectivity qnetworkaccessmanager qtimer qnetworkreply

我们正面临着QNetworkAccessManager和QTimers用于网络超时检测的计时问题。虽然,我们不清楚何时启动这些QTimers。

我们的第一次尝试是在get请求后直接启动计时器。但这会导致高负荷下的过早中止。显然,QNetworkAccessManager会自行排队,并且在将请求发送到线路之前会触发超时。

QNetworkReply *reply = _qnam->get(someRequest);

// connect standard handlers of our application
QObject::connect(reply, &QNetworkReply::finished, [reply] {
    handle(reply);
});

// do timeout handling using QTimers in "global" scope
timeoutTimer.setSingleShot(true);
QObject::connect(&timeoutTimer, &QTimer::timeout, [reply] { reply->abort(); });
timeoutTimer.start(timeout);

第二次尝试是在第一个QNetworkAccessManager::uploadProgress()QNetworkAccessManager::uploadProgress()内启动计时器,但这在没有任何网络连接的情况下不起作用。显然,从来没有任何进展报告,并且首先没有开始超时。

QNetworkReply *reply = _qnam->get(someRequest);

// connect standard handlers of our application
QObject::connect(reply, &QNetworkReply::finished, [reply] {
    handle(reply);
});

// do timeout handling using QTimers in "global" scope
auto timerSetOrReset = [reply] {
    if (!timeoutTimer.isActive()) {
        timeoutTimer.setSingleShot(true);
        QObject::connect(&timeoutTimer, &QTimer::timeout, [reply] { reply->abort(); });
    }

    timeoutTimer.start(timeout);
};

QObject::connect(reply, &QNetworkReply::uploadProgress,   timerSetOrReset);
QObject::connect(reply, &QNetworkReply::downloadProgress, timerSetOrReset);

感觉我们不能成为第一个面对这个问题的人。

谢谢!

0 个答案:

没有答案