I am using warmcat\'s libwebsocket C library for a small websocket server. I have the examples up and working and can send data in response to receiving data from the websocket
I haven't found a super clean way of doing that. What I would suggest is to register a callback on the event that server can write to the client and then check if there's asynchronous work to send there. the LWS_CALLBACK_SERVER_WRITEABLE
event is just that, and if you call libwebsocket_callback_on_writable(context, wsi);
from within your callback it'll be periodically called.
So, something like this:
static int callback_myprotocol(struct libwebsocket_context *context,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason,
void *user, void *in, size_t len)
{
SendState *ss = (SendState*)user;
switch (reason) {
case LWS_CALLBACK_ESTABLISHED:
printf("connection established\n");
// get the ball rolling
libwebsocket_callback_on_writable(context, wsi);
break;
case LWS_CALLBACK_SERVER_WRITEABLE: {
if (!work_to_be_done) {
// schedule ourselves to run next tick anyway
libwebsocket_callback_on_writable(context, wsi);
return 0;
}
// send our asynchronous message
libwebsocket_write(wsi, buf, size, flag);
// and schedule ourselves again
libwebsocket_callback_on_writable(context, wsi);
break;
}
default:
break;
}
return 0;
}
I adapted this from the test-fraggle.c
example; the above is roughly what that example does to send messages in smaller chunks.