Friday, September 16, 2011

Asynchronous non blocking curl multi example in C++

The curl documentation makes me want to cry.

The library seems nice enough and if you want to do some blocking synchronous http requests (and print them out to the standard out) then it's extremely straight forward.

But who wants to do blocking requests? There are very few programs that can get away with locking entirely until a http request is done.

Also one my internet pet-peeves, when searching for solutions I often come upon threads or mailing lists with someone stating my exact problem and then a reply saying read the docs. It would be so much nicer, internet, if the question had been answered right there and then.

Anyway here's the rough equivalent of simple.c in the examples but using the multi interface so it doesn't block.

The header.
class Http
 CURLM* multi_handle; 
 int handle_count;

  void Update();
  void AddRequest(const char* uri);

The implementation.
 multi_handle = curl_multi_init();
 handle_count = 0;


void Http::Update()
 curl_multi_perform(multi_handle, &handle_count);

void Http::AddRequest(const char* uri)
  CURL* curl = NULL;
  curl = curl_easy_init();
  curl_easy_setopt(curl, CURLOPT_URL, uri);
  curl_multi_add_handle(multi_handle, curl);

First thing to note - the curl pointer is never released! That needs to be taken care of.

The code can be used like

Http http;

// In some update loop called each frame
That will then print the google homepage out to the standard out. Also a good guide to building Curllib can be found here:
Post a Comment