libcurl下载限速编程调研
生活随笔
收集整理的這篇文章主要介紹了
libcurl下载限速编程调研
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目前的業務需求是, 要求下載過程中, 能夠恰當控制下載速度?
如何實現? 我想到了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 Filefp = 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/scurl_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 resourcescurl_easy_cleanup (curl);//Close the filefclose (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的限速功能還是很靠譜的.
總結
以上是生活随笔為你收集整理的libcurl下载限速编程调研的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用C++ stringstream来进
- 下一篇: printf格式化输出几点注记