Skip to content

Instantly share code, notes, and snippets.

@stevenwilkin
Last active December 23, 2024 06:10
Show Gist options
  • Save stevenwilkin/8fce850e825817319ab3e71a1745693d to your computer and use it in GitHub Desktop.
Save stevenwilkin/8fce850e825817319ab3e71a1745693d to your computer and use it in GitHub Desktop.
Minimal libwebsockets client to read from Binance. Compile with `gcc -obinance binance.c -lwebsockets`
#include <stdio.h>
#include <stdbool.h>
#include <signal.h>
#include <libwebsockets.h>
static bool bExit;
static int callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len);
static const struct lws_protocols protocols[] = {
{ "lws-minimal-client", callback, 0, 0, 0, NULL, 0 },
LWS_PROTOCOL_LIST_TERM
};
static const struct lws_extension extensions[] = {
{
"permessage-deflate",
lws_extension_callback_pm_deflate,
"permessage-deflate"
"; client_no_context_takeover"
"; client_max_window_bits"
},
{ NULL, NULL, NULL /* terminator */ }
};
static int callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) {
switch (reason) {
case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
printf("error: %s\n", in ? (char *)in : "(null)");
return -1;
case LWS_CALLBACK_CLIENT_RECEIVE:
printf("%s\n", (char *)in);
break;
case LWS_CALLBACK_CLIENT_ESTABLISHED:
printf("connected\n");
break;
case LWS_CALLBACK_CLIENT_CLOSED:
printf("closed\n");
bExit = true;
return -1;
default:
break;
}
return 0;
}
static void handle_sigint(int sig) {
bExit = true;
}
int main(int argc, const char **argv) {
struct lws_context *context;
struct lws_client_connect_info i;
struct lws_context_creation_info info;
lws_set_log_level(LLL_ERR | LLL_WARN, lwsl_emit_syslog); // We don't need to see the notice messages
signal(SIGINT, handle_sigint);
memset(&i, 0, sizeof(i));
memset(&info, 0, sizeof info);
info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
info.port = CONTEXT_PORT_NO_LISTEN; /* we do not run any server */
info.protocols = protocols;
info.fd_limit_per_thread = 1 + 1 + 1;
info.extensions = extensions;
context = lws_create_context(&info);
if (!context) {
printf("error creating context\n");
return -1;
}
i.context = context;
i.port = 9443;
i.address = "stream.binance.com";
i.path = "/ws/btcusdt@aggTrade";
i.host = i.address;
i.origin = i.address;
i.ssl_connection = LCCSCF_USE_SSL | LCCSCF_PRIORITIZE_READS;
i.protocol = NULL;
i.local_protocol_name = "lws-minimal-client";
if (!lws_client_connect_via_info(&i)) {
printf("error connecting\n");
return -1;
}
while (!bExit) {
lws_service(context, 0);
}
lws_context_destroy(context);
printf("finished\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment