Handling network timeout in Qt

霸气de小男生 提交于 2019-12-06 05:58:54

问题


When dealing with QNetworkReply, it is prescribed to use timers to abort the connection.

Here is my current code:

void ImageDownloader::download(QString imgUrl){    
  this->timeoutTimer = new QTimer(this);
  this->timeoutTimer->setSingleShot(true);
  this->timeoutTimer->setInterval(15000);
  connect(this->timeoutTimer, SIGNAL(timeout()), this, SLOT(timeout()));

  QUrl requestUrl(imgUrl);
  QNetworkRequest nwRequest(requestUrl);
  this->imageNwReply = this->nam->get(nwRequest);
  connect(imageNwReply,SIGNAL(finished()),this,SLOT(imgDownloaded()));
  connect(imageNwReply, SIGNAL(downloadProgress(qint64,qint64)), this->timeoutTimer, SLOT(start()));
  this->timeoutTimer->start();
}

void ImageDownloader::timeout(){
  qDebug()<<__FUNCTION__<<" Forced timeout!";    
  this->imageNwReply->abort();
}

The confusion I am facing is when should I start the timer? At times I have to make around 50 concurrent Get requests from QNetworkAccessManager but since there is throttling for maximum concurrent connections, at times it happens that some of the requests get timed out even before they have been processed.

Is there a signal to know exactly when the processing for a request is started by QNeworkAccessManager so that I can start the corresponding timer only then?

One possible solution might be to implement a Queue of requests and have only the maximum possible connections to process but I am looking for a cleaner solution


回答1:


There is an open bug/enhancement request for the issue. I got to know about this bug from Qt forum



来源:https://stackoverflow.com/questions/12002605/handling-network-timeout-in-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!