为什么客户端 websocket 关闭代码与服务器代码不匹配?

Why do client websocket close codes not match the server code?

我有一个 Spring 引导 Tomcat 服务器正在处理来自使用以下客户端的 websocket 连接:

  1. 套接字火箭
  2. 泰鲁斯

我发现服务端提供的关闭码往往不是客户端读取的关闭码

对于SocketRocket,我在服务端用code 1000关闭websocket,客户端经常读取1001。

对于 Tyrus,我使用代码 1011 关闭了 websocket,客户端读取 1006 或 1011。

来自 RFC 6455 的关闭代码说明:

1000 indicates a normal closure, meaning that the purpose for which the connection was established has been fulfilled.

1001 indicates that an endpoint is "going away", such as a server going down or a browser having navigated away from a page.

1006 is a reserved value and MUST NOT be set as a status code in a Close control frame by an endpoint. It is designated for use in applications expecting a status code to indicate that the connection was closed abnormally, e.g., without sending or receiving a Close control frame.

1011 indicates that a server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.

我已经在服务器上使用 Wireshark 验证了传出关闭代码。

作为从服务器向客户端传递信息的方式,关闭代码是否不可靠?在关闭 websockets 之前,我是否需要在传递此信息的应用层实现一些东西?

这只是一个猜测,但您列出的 WebSocket 客户端可能无法正确实现关闭握手。

为什么不试试 nv-websocket-client to see what's happening? onDisconnected method of the library's listener interface (WebSocketListener) 定义如下。

void onDisconnected(
        WebSocket websocket,
        WebSocketFrame serverCloseFrame,
        WebSocketFrame clientCloseFrame,
        boolean closedByServer);

第二个参数serverCloseFrame是服务器发送给客户端的关闭帧,第三个参数clientCloseFrame是客户端发送给服务器的关闭帧。正常情况下,按照规范的要求,两个相近帧的载荷是相同的。