问题
I'm using the QNetworkAccessManager to download files from the web, it provides an easy API to the task. But I wish to add a download rate limit to the class, so all http replies won't exceed that limit (I see no reason to limit the requests).
I've googled abit and found an interesting post here. But what it does is subclass QTcpSocket and gives control over the bandwidth using a separate class that manages a set of sockets. While this is nice I want to continue using the QNetworkAcessManager class.
The way I see it I could:
- subclass QNetworkAccessManager and integrate the subclassed QTcpSocket somehow (this might involve subclassing even more classes, the QHttp* ones).
- use the classes offered in the article and build my own QNetworkAccessManager around those.
- the QNetworkAccessManager allows the use of a proxy. I could write a fake proxy class that will have the bandwidth throttling logic in it. But this seems like an ugly hack to me.
While the first 2 options are possible, I was wondering if there's an easier way to do this? If not which one would you suggest?
回答1:
I ended up using the RcTcpSocket and RateController from this article with the QHttp class. Prior to making get/post requests with the QHttp I create a RcTcpSocket, add it to my RateController and use QHttp::setSocket(QTcpSocket*). I still didn't find a solution to keep using QNetworkAccessManager but this is close enough and works very good.
回答2:
You should have a look at QNetworkReply::setReadBufferSize(qint64 size). I quote the doc:
QNetworkReply will try to stop reading from the network once this buffer is full (i.e., bytesAvailable() returns size or more), thus causing the download to throttle down as well. If the buffer is not limited in size, QNetworkReply will try to download as fast as possible from the network.
I guess you could play on this value, and maybe the value you get from the downloadProgress() signal to slow things down. I think it should be pretty hard to get something precise with it, but it's probably doable.
来源:https://stackoverflow.com/questions/729792/bandwidth-throttling-with-qt