How to do curl_multi_perform() asynchronously in C++?

前端 未结 1 699
一整个雨季
一整个雨季 2020-12-25 08:40

I have come to use curl synchronously doing a http request. My question is how can I do it asynchronously?

I did some searches which lead me to the docu

相关标签:
1条回答
  • 2020-12-25 09:18

    Read the documentation again more carefully, particularly these portions:

    http://curl.haxx.se/libcurl/c/libcurl-multi.html

    Your application can acquire knowledge from libcurl when it would like to get invoked to transfer data, so that you don't have to busy-loop and call that curl_multi_perform(3) like crazy. curl_multi_fdset(3) offers an interface using which you can extract fd_sets from libcurl to use in select() or poll() calls in order to get to know when the transfers in the multi stack might need attention. This also makes it very easy for your program to wait for input on your own private file descriptors at the same time or perhaps timeout every now and then, should you want that.

    http://curl.haxx.se/libcurl/c/curl_multi_perform.html

    When an application has found out there's data available for the multi_handle or a timeout has elapsed, the application should call this function to read/write whatever there is to read or write right now etc. curl_multi_perform() returns as soon as the reads/writes are done. This function does not require that there actually is any data available for reading or that data can be written, it can be called just in case. It will write the number of handles that still transfer data in the second argument's integer-pointer.

    If the amount of running_handles is changed from the previous call (or is less than the amount of easy handles you've added to the multi handle), you know that there is one or more transfers less "running". You can then call curl_multi_info_read(3) to get information about each individual completed transfer, and that returned info includes CURLcode and more. If an added handle fails very quickly, it may never be counted as a running_handle.

    When running_handles is set to zero (0) on the return of this function, there is no longer any transfers in progress.

    In other words, you need to run a loop that polls libcurl for its status, calling curl_multi_perform() whenever there is data waiting to be transferred, repeating as needed until there is nothing left to transfer.

    The blog article you linked to mentions this looping:

    The code can be used like

    Http http;
    http:AddRequest("http://www.google.com");

    // In some update loop called each frame
    http:Update();

    You are not doing any looping in your code, that is why your callback is not being called. New data has not been received yet when you call curl_multi_perform() one time.

    0 讨论(0)
提交回复
热议问题