[Libwebsockets] Sending WS Connection Close packet immediately from the lws client

Andy Green andy at warmcat.com
Tue May 21 14:51:33 CEST 2019

On 5/21/19 1:42 PM, Mateusz Stępień wrote:
> Hello,
> I'm trying to send Connection Close packet on user requested 
> disconnection. Right now, I found that the only way to send this packet 
> is to call lws_close_reason in a LWS_CALLBACK_CLIENT_RECEIVE callback 
> and return -1 from it, e.g.
> void disconnect(struct user_data* user_data)
> {
>      user_data->completed = 1;
> }
> in lws callback:
> int callback(struct lws *wsi, enum lws_callback_reasons reason, void 
> *user, void *in, size_t len)
> {
>      struct user_data* user_data = user;
>      if(reason == LWS_CALLBACK_CLIENT_RECEIVE && user_data->completed)
>      {
>          lws_close_reason(wsi, LWS_CLOSE_STATUS_NORMAL, NULL, 0);
>          return -1;
>      }
> }
> But this solution is not very robust, because actual packet sending 
> cannot happen immediately after calling disconnect() function. The 

There's also this api


You can never guarantee you can either send the close frame at all or 
when you can send it.  If it can be sent within a timeout period of a 
few seconds, it will be sent.  But anything can crash or run out of 
battery or lose connection at any time without ceremony.  So you 
shouldn't assume this can be made a certainty... CLOSE callback to learn 
the socket closed is much more certain.


More information about the Libwebsockets mailing list