Is it possible to control download speed using QNetworkAccessManager
-
What about reducing the "read buffer size":http://doc.qt.nokia.com/4.7-snapshot/qnetworkreply.html#setReadBufferSize and clearing the buffer at the desired download rate?
-
The download should just stall, which means it stops receiving data after 512 kB and waits for the buffer to be emptied. It then continous receiving the next 512 kB of data once done so.
I haven't verified this, but if you set your read buffer to for example 512 kB an you empty it once a second (using read()), you should theoretically end up with an download rate of (approx.) 512 kB a second.
-
When readyRead() signal is emitted then the following slot is invoked
@void Download::saveToDisk()
{qint64 bytes; bytes=replySegment->bytesAvailable(); fileSegment.write(replySegment->read(bytes));
}@
How, can i control it using QTimer, it is completely determined by the readyRead() signal. Can you plz explain it more
-
No, it isn't. ;-)
Just ignore the readyRead() signal and use a QTimer, which periodically empties the read buffer.
@
class Downloader : public QObject
{
Q_OBJECTpublic:
Downloader(QObject *object) : QObject(parent)
{
timer.setInterval(1000);
connect(&timer, SIGNAL(timeout()), this, SLOT(processData());
}bool download(const QUrl &url, const QString &fileName, downloadRate = -1) { file.setFileName(fileName); if (file.open(QIODevice::WriteOnly | QIODevice::Truncate) == false) return false; reply = manager.get(QNetworkRequest(url)); if (downloadRate > 0) reply->setReadBufferSize(downloadRate); timer.start(); return true; }
signals:
void finished();private:
QNetworkAccessManager manager;
QNetworkReply *reply;
QTimer timer;private slots:
void processData()
{
file.write(reply->read(reply->bytesAvailable()));if (reply->isFinished() == true) { timer.stop(); file.close(); reply->deleteLater(); reply = nullptr; emit finished(); } }
@
Brain to terminal. Not tested. Exemplary.