Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LibCurl WriteCallback (Async?) - C++

Tags:

c++

curl

libcurl

I am successfully making an http POST call using the following code:

std::string curlString;
CURL* pCurl = curl_easy_init();

if(!pCurl)
    return NULL;

string outgoingUrl = Url;
string postFields = fields;

curl_easy_setopt(pCurl, CURLOPT_TIMEOUT, 0);

curl_easy_setopt(pCurl, CURLOPT_URL, outgoingUrl.c_str());
curl_easy_setopt(pCurl, CURLOPT_POST, 1);

curl_easy_setopt(pCurl, CURLOPT_POSTFIELDS, postFields.c_str());
curl_easy_setopt(pCurl, CURLOPT_POSTFIELDSIZE, (long)postFields.size());

curl_easy_setopt(pCurl, CURLOPT_WRITEFUNCTION, CurlWriteCallback);
curl_easy_setopt(pCurl, CURLOPT_WRITEDATA, &curlString);

curl_easy_perform(pCurl);

curl_easy_cleanup(pCurl);

The write callback has the following prototype:

size_t CurlWriteCallback(char* a_ptr, size_t a_size, size_t a_nmemb, void* a_userp);

Is there a way to do this asynchronously? Currently it waits for the callback to finish before curl_easy_perform returns. This blocking method won't work for a server with many users.

like image 258
Josh Brittain Avatar asked Aug 16 '12 03:08

Josh Brittain


1 Answers

From the libcurl easy documentation:

When all is setup, you tell libcurl to perform the transfer using curl_easy_perform(3). It will then do the entire operation and won't return until it is done (successfully or not).

From the libcurl multi interface docs, one of the features as opposed to the "easy" interface:

  1. Enable multiple simultaneous transfers in the same thread without making it complicated for the application.

Sounds like you want to use the "multi" approach.

like image 63
FriendFX Avatar answered Nov 07 '22 08:11

FriendFX