[Libwebsockets] how to send a message to all connected clients?

Glaudiston Gomes da Silva glaudistong at gmail.com
Sun Jan 25 21:43:24 CET 2015


Hello,

I'm trying to use libwebsockets in my application as server, for this
I'm using the echo test as sample code, for client-server
communication, all get well, but  I'm trying to do a function that
notify all connected clients sockets when a new client arrive or
leave.

My code runs ok on first connection and notify the client, but on
second one it generate a seg fault. I think may be the library
provides me a nice way to do this. but here my code:

To do this, I do created a struct:
> struct WSSession {
>         struct libwebsocket_context *context;
>         struct libwebsocket *wsi;
> };
>
> int wssession_count=0;
>
> struct WSSession ** wssession;

and a notify_all function:
> void notify_all(enum libwebsocket_callback_reasons reason){
>         int i, n;
>         for ( i=0; i<wssession_count; i++ ){
>         switch (reason) {
>         case LWS_CALLBACK_ESTABLISHED:
>                 // n = libwebsocket_write(wssession[i]->wsi, "abcd\0", 5, LWS_WRITE_TEXT);
>                 libwebsocket_callback_on_writable(wssession[i]->context, wssession[i]->wsi);
>                 break;
>         case LWS_CALLBACK_CLOSED:
>                 //int n = libwebsocket_write(wssession[i]->wsi, &resp.buf[0], resp.len, LWS_WRITE_TEXT);
>                 // libwebsocket_callback_on_writable(wssession[i]->context, wssession[i]->wsi);
>                 break;
>         default:
>                 break;
>         }
>         }
> }



So, in callback_echo function I have added the block for
LWS_CALLBACK_ESTABLISHED:
>
> callback_echo(struct libwebsocket_context *context, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len)
> {
> ...
>         case LWS_CALLBACK_ESTABLISHED:
>                 lwsl_notice("Client connected \n");
>                 struct WSSession ** wsc = realloc( wssession, sizeof(struct WSSession) * ++wssession_count );
>                 if ( wsc == NULL ) {
>                         lwsl_err("ERROR Fail to realloc for wssession number %i, hanging up.\n", wssession_count );
>                         return 1;
>                 }
>                 wssession=wsc;
>
>                 wssession[wssession_count-1]->context=context;
>                 wssession[wssession_count-1]->wsi=wsi;
>                 notify_all(reason);
>                 break;


Anyone can help me understand why it's wrong and what is the correct
way to do it ?



More information about the Libwebsockets mailing list