Reputation: 522
I want to create a web application where a group of users could receive some data asynchronously whenever the C++ backend have something new. So, ideally, when a new user comes, he'll be added to the subscribers list and whenever the C++ backend has new data for the group, it will publish it to everybody.
libwebsockets seems to be a good library to use with C++. The only problem is that it seems that it's mainly designed on a callback system, so, apparently data is meant to be sent only if the client asks for it.
I found this post with a similar issue but I don't know if this is the best way to do that: How do I send async data via libwebsocket?
Any help will be appreciated. Thank you.
Upvotes: 1
Views: 1164
Reputation: 522
found it!
libwebsockets lets you broadcast to all connected users to a specific protocol using libwebsocket_callback_on_writable_all_protocol(*protocol)
which triggers LWS_CALLBACK_SERVER_WRITEABLE
that will be handled by the protocol's callback function and that's where we could send the data.
So, typically, I use my second protocol (the non-http one) whenever I have some data to broadcast in any part of my code with libwebsocket_callback_on_writable_all_protocol(protocols + 1)
and in the protocol's callback function
static int callback_linux_shell(struct libwebsocket_context * context, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len) {
switch (reason) {
...
case LWS_CALLBACK_SERVER_WRITEABLE:
libwebsocket_write(wsi, my_data, my_data_size, LWS_WRITE_TEXT);
break;
...
}
}
Upvotes: 1