Search code examples
clibcurlpushbullet

libcurl continue running after writefunction callback


I am trying to use the libcurl library in C with the pushbullet api. I am trying to connect to a stream at https://stream.pushbullet.com/streaming/. The problem is once the callback function is called when it receives any data, the connection is closed. I would like to keep it running indefinitely and have it call the callback function be called every time it receives new data.

Here is the code I tried

#include <stdio.h>
#include <string.h>
#include <curl/curl.h>

int getwss_cb(char *data) {
    printf("Received data: %s\n", data);
}

int getwss(void) {
    CURL *easyhandle = curl_easy_init();

    curl_easy_setopt(easyhandle, CURLOPT_URL, "https://stream.pushbullet.com/streaming/<access-token>");
    curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, getwss_cb);
    curl_easy_perform(easyhandle);
    return 0;
}

Basically I need the getwss() function to continue running even after running getwss_cb()


Solution

  • Your callback doesn't use the correct prototype and it doesn't return the correct return code:

    size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata);
    

    See the full docs explaining the callback and what it should return in the documentation for the CURLOPT_WRITEFUNCTION option.

    Also note that the data that is passed to the callback is not zero terminated so you can't just printf-%s it.