目前的业务需求是, 要求下载过程中, 能够恰当控制下载速度?
如何实现? 我想到了libcurl中提供的下载限速选项.现在探讨如下.
我找到Ubuntu 14.04.01的iso大文件, 使用libcurl来限速下载, 参见下图:
下面是相关的源码
//g++ -g curl_speed.cpp -o curl_speed -lcurl
//
#include <stdio.h>
#include <iostream>
#include <string>
#include <curl/curl.h>
using namespace std;
int download (string url, string local_file, int down_speed)
{
CURL *curl;
CURLcode res;
FILE *fp;
curl = curl_easy_init ();
if (curl)
{
//Open File
fp = fopen (local_file.c_str (), "w");
if (fp == NULL)
cout << "File cannot be opened" << endl;
curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, NULL);
curl_easy_setopt (curl, CURLOPT_WRITEDATA, fp);
curl_easy_setopt (curl, CURLOPT_URL, url.c_str ());
curl_easy_setopt (curl, CURLOPT_FOLLOWLOCATION, 1);
//这里限速 100KB/s
curl_easy_setopt (curl, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t) down_speed * 1024);
curl_easy_setopt (curl, CURLOPT_NOPROGRESS, 0);
// curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
//限速下载
res = curl_easy_perform (curl);
if (res)
cout << "Cannot grab the File!\n";
}
//Clean up the resources
curl_easy_cleanup (curl);
//Close the file
fclose (fp);
return 0;
}
int main (int argc, char *argv[])
{
string url ("http://cdimage.ubuntu.com/releases/14.04/release/ubuntu-14.04-desktop-amd64+mac.iso");
//string url("http://m4.biz.itc.cn/pic/new/n/15/78/Img7087815_n.jpg");
string filepath ("./a.jpg");
int downspeed = 600;
int ret = download (url, filepath, downspeed);
cout << "download [result]: " << ret << endl;
return 0;
}
下面是不同限速下面的程序截图,分别对应50, 200, 600kb/s的限速设置
从截图可以看出, 设置限速600kb/s时, 已经达到我所在网络所能下载的极限, 所以数据下载过程中, 波动比较大, 但都不会超过600kb/s的上限.
看来, libcurl的限速功能还是很靠谱的.