[Libwebsockets] ws client initiated close frame?

Andy Green andy at warmcat.com
Tue Mar 5 22:21:21 CET 2019



On 06/03/2019 04:51, Dave Horton wrote:
> I have an websocket client that is working fine, however currently when I close the websocket from the client side the ws server (non-lws) generates an exception (err: 1006).

1006 just means the socket closed.

> I am closing the socket simply by returning -1 from my LWS_CALLBACK_CLIENT_WRITEABLE, which I think per the documentation is the recommended way.

If lws thinks it's possible, it will send a logical CLOSE message and 
then close.  If it thinks it may not be possible, it will just close the 
connection.

> When I take a network capture I see that this closes the TCP socket.  Again, fine, but from reading the spec (https://tools.ietf.org/html/rfc6455#section-5.5.1),
> I am wondering if the issue is that the server is expecting me to send a CLOSE frame.

Yes, 1006 is reserved to indicate the socket closed without a CLOSE. 
It's not illegal to do so, sockets can close at any time for a variety 
of reasons and the server handled it fine.

> Is there a way for my lws client to send a CLOSE frame as part of shutdown?

It tries to do it.  But it cannot guarantee it under all conditions. 
Eg, TLS tunnel error, intermediate router rebooted, client itself 
rebooted, ran out of metered internet etc etc will all end up with a 
unceremoniously closed ws connection.  There are also conditions you 
want to close with an ongoing incomplete message fragment, it cannot 
succeed.

So you can't leave this as an uncaught exception serverside... it's a 
normal part of life that should be handled.

> The spec further seems to say that the connection SHOULD be first closed from the server (https://tools.ietf.org/html/rfc6455#section-7.1.1).
> 
> I’m just wondering if I am doing things correctly with regard to the scenario of web socket client-initiated close…

You can arrange to provide your own CLOSE reason

https://libwebsockets.org/git/libwebsockets/tree/include/libwebsockets/lws-ws-close.h

 > OK, scratch that.  My problem was that I wasn’t calling
 > lws_close_reason() before returning -1.

Great.  But 1006 uncontrolled closes are still a thing... the server 
side TLS may find something wrong with what it received for example and 
close the socket immediately, without the client being involved.

-Andy

> Dave
> _______________________________________________
> Libwebsockets mailing list
> Libwebsockets at ml.libwebsockets.org
> https://libwebsockets.org/mailman/listinfo/libwebsockets
> 


More information about the Libwebsockets mailing list