[Libwebsockets] What is the correct way to close a WS client connection?

andy at warmcat.com andy at warmcat.com
Sat May 9 01:05:36 CEST 2020



On May 8, 2020 9:44:34 PM UTC, Olivier Langlois <olivier at olivierlanglois.net> wrote:
>I want to implement an inactivity timer because my WS client has just
>sit idle since I have rebooted my router at home yesterday evening.
>I want lws to initiate a WS client close so that the lws callbacks
>trigger my reconnection code.

Lws has a smart 'connection validity' management that will provoke PING type probing if it hasn't seen something prove the connection is valid for some time.  See the second part here

https://libwebsockets.org/git/libwebsockets/tree/READMEs/README.lws_retry.md

Since either side can fail in a sneaky way you can only go off tranactions that can only happen if the peer both must have received your rx and you can receive his rx, ie, a ping / pong.  If ypu have your own bidi transactions happening, you can report them and optimize how many ping probes you're generating that way.

>By trying to plan how I'll do that, I have figure that beside when I
>shutdown the process and clean-up lws, that is the only way that I
>currently initiate a connection shutdown. Beside that unique situation,
>I simply react passively to events received in the callback to process
>reconnections when lws reports a connection error or that the server
>close the connection.
>
>What is the function to call to let lws know that we want to close a ws
>client socket?

https://libwebsockets.org/git/libwebsockets/tree/include/libwebsockets/lws-timeout-timer.h#n77-101

But you definitely want the validity management, protocol-indepent PING generation (for h2 and ws), automatic connection close and the retry / backoff stuff.  Then you don't need a manual close.

>In lws-client.h where the connect function is, there is no equivalent
>close function. There is also a lws-ws-close.h providing a
>lws_close_reason(). It isn't 100% clear lws_close_reason() actually
>perform the close. It is used by the library and it seems to be for
>setting the reason after the fact that something did trigger a
>connection shutdown.
>
>A little help for this simple issue would be welcome.

Doing it properly is not that simple...

-Andy

>thx,
>Olivier


More information about the Libwebsockets mailing list