#include <libwebsockets.h>
#include <uv.h>
static struct lws_context *context;
static struct lws *web_socket = NULL;
static void my_uv_timeout_cb(uv_timer_t *w) {
lws_callback_on_writable_all_protocol(context, &protocols[0]);
uv_timer_start(w, my_uv_timeout_cb, 50, 0);
}
static int callback_my_protocol(struct lws *wsi, enum lws_callback_reasons reason,
void *user, void *in, size_t len) {
switch (reason) {
case LWS_CALLBACK_CLIENT_ESTABLISHED:
lwsl_user("Client connection established\n");
break;
case LWS_CALLBACK_CLIENT_WRITEABLE:
// TODO: Write data to WebSocket
break;
case LWS_CALLBACK_CLIENT_RECEIVE:
// TODO: Process received data
break;
default:
break;
}
return 0;
}
static const struct lws_protocols protocols[] = {
{
"my-protocol",
callback_my_protocol,
0,
128,
},
{ NULL, NULL, 0, 0 } /* terminator */
};
int main() {
struct lws_context_creation_info info;
struct lws_client_connect_info i;
memset(&info, 0, sizeof info);
info.options = LWS_SERVER_OPTION_LIBUV;
info.protocols = protocols;
info.gid = -1;
info.uid = -1;
info.ws_ping_pong_interval = 10;
context = lws_create_context(&info);
if (!context) {
lwsl_err("Error creating context\n");
return 1;
}
uv_loop_t *loop = lws_uv_getloop(context, 0);
struct sockaddr_in addr;
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
i.context = context;
i.ssl_connection = 0;
i.host = "localhost";
i.method = "GET";
i.address = "localhost";
i.protocol = protocols[0].name;
i.path = "/";
i.port = 8080;
i.local_client_bind_address = (struct sockaddr *)&addr;
i.socklen = sizeof(addr);
web_socket = lws_client_connect_via_info(&i);
if (!web_socket) {
lwsl_err("Error connecting to WebSocket\n");
return 1;
}
uv_timer_t my_uv_timer;
uv_timer_init(loop, &my_uv_timer);
uv_timer_start(&my_uv_timer, my_uv_timeout_cb, 50, 0);
uv_run(loop, UV_RUN_DEFAULT);
lws_context_destroy(context);
lwsl_user("Exiting...\n");
return 0;
}