首页 > 解决方案 > 使用 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++filehttpasynchronouslibcurl

解决方案


推荐阅读