c++ - 使用 libcurl“多”接口进行单个文件下载 - C++
问题描述
我正在创建一个 C++ dll,我需要发出一个非阻塞 http 请求。我的意思是,在dll中的某个点,我需要在后台启动文件的下载,但在启动单次下载后恢复程序。
我目前使用 libcurl 作为我的 http 客户端。我读到多接口(https://curl.haxx.se/libcurl/c/libcurl-multi.html)将为我提供非阻塞功能,但我看到的所有示例都是同时发出多个 http 请求,并等待所有这些都完成 w/a while 循环。我是否可以使用此接口发出单个 http 请求,并在下载程序时恢复程序?如果是这样,它可以在完成时触发回调吗?还是我必须不断检查句柄以查看下载是否完成?
带有 libcurl 多接口的单个请求示例:
int main() {
curl_global_init(CURL_GLOBAL_DEFAULT);
// init easy curl session
auto curl_easy = curl_easy_init();
// set url
auto url = "https://[foo].exe";
curl_easy_setopt(curl_easy, CURLOPT_URL, url);
// set curl to write file to directory
auto path = "C:\\foo\\app.exe";
auto filePtr = std::fopen(path, "wb");
curl_easy_setopt(curl_easy, CURLOPT_WRITEFUNCTION, writeFile);
curl_easy_setopt(curl_easy, CURLOPT_WRITEDATA, filePtr);
// init multi curl session
auto multi_handle = curl_multi_init();
// add easy handle to multi handle
curl_multi_add_handle(multi_handle, curl_easy);
auto res = curl_multi_perform(multi_handle, &running);
auto running = 0;
while (running) {
res = curl_multi_perform(multi_handle, &running);
}
我不想while (running)
在文件下载时执行循环并在 main 中执行其他操作。我可能误解了 curl_multi_perform() 的“非阻塞”性质。仅在许多请求可以同时发生的意义上它是非阻塞的吗?如果是这样,我认为使用它来发出单个请求不会让我得到 curl_easy_perform 所没有的任何东西。抱歉,如果这超出了堆栈溢出的范围,我不想要 libcurl 教程。但是我是否应该在 std::async() 内部使用阻塞 libcurl 调用 (curl_easy_perform) 之类的东西?
解决方案
推荐阅读
- c++ - 嵌套模板的拆分模板类定义和声明失败
- python - 从日志文件中提取每个 TagId 的 RSSI、Lat、Lng
- java - 我想获取仅按用户名过滤的信息
- reactjs - 如何为不同的功能设置不同的ajax调用数据 - Jest Enzyme
- boost - 提高 stop() 的 msm 使用率
- amazon-web-services - 将 AWS 机密复制到另一个账户
- rxjs - 处理 rxjs lastValueFrom 中的 http 错误
- kubernetes - 通过 Terraform 为自动扩展 kubernetes 集群设置启动磁盘大小
- python-3.x - 寻找通用 Swagger 解析器实用程序以在 python 中自动化
- ios - 使用 Shell 的 iPad 不会填充纵向,但会缩放到横向