libcurl下载限速编程调研
生活随笔
收集整理的這篇文章主要介紹了
libcurl下载限速编程调研
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
目前的業(yè)務(wù)需求是, 要求下載過(guò)程中, 能夠恰當(dāng)控制下載速度?
如何實(shí)現(xiàn)? 我想到了libcurl中提供的下載限速選項(xiàng).現(xiàn)在探討如下.
我找到Ubuntu 14.04.01的iso大文件, 使用libcurl來(lái)限速下載, 參見(jiàn)下圖:
下面是相關(guān)的源碼
//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;
}
下面是不同限速下面的程序截圖,分別對(duì)應(yīng)50, 200, 600kb/s的限速設(shè)置
從截圖可以看出, 設(shè)置限速600kb/s時(shí), 已經(jīng)達(dá)到我所在網(wǎng)絡(luò)所能下載的極限, 所以數(shù)據(jù)下載過(guò)程中, 波動(dòng)比較大, 但都不會(huì)超過(guò)600kb/s的上限.
看來(lái), libcurl的限速功能還是很靠譜的.
總結(jié)
以上是生活随笔為你收集整理的libcurl下载限速编程调研的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 使用C++ stringstream来进
- 下一篇: printf格式化输出几点注记