正确主动关闭websocket,异常关闭处理

CloseEvent.code

开发大型项目时需要正确主动关闭websocket,同时根据异常关闭正确的执行重连

  • 0-999 暂未使用
关闭状态码 简称 原因
1000 正常关闭 连接成功地完成了创建它的目的。
1001 离开 端点消失了,可能是因为服务器故障,也可能是因为浏览器离开了打开连接的页面。
1002 协议错误 由于协议错误,端点正在终止连接。
1003 不支持的数据 由于端点接收到的数据类型无法接受,连接被终止。(例如,纯文本端点接收二进制数据
1004 暂时保留 保留。将来可能会定义一个含义。
1005 No Status Rcvd Reserved. Indicates that no status code was provided even though one was expected.
1006 Abnormal Closure Reserved. Indicates that a connection was closed abnormally (that is, with no close frame being sent) when a status code is expected.
1007 Invalid frame payload data The endpoint is terminating the connection because a message was received that contained inconsistent data (e.g., non-UTF-8 data within a text message).
1008 Policy Violation The endpoint is terminating the connection because it received a message that violates its policy. This is a generic status code, used when codes 1003 and 1009 are not suitable.
1009 Message Too Big The endpoint is terminating the connection because a data frame was received that is too large.
1010 Mandatory Ext. The client is terminating the connection because it expected the server to negotiate one or more extension, but the server didn’t.
1011 Internal Error The server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.
1012 Service Restart The server is terminating the connection because it is restarting.
1013 Try Again Later The server is terminating the connection due to a temporary condition, e.g. it is overloaded and is casting off some of its clients.
1014 Bad Gateway The server was acting as a gateway or proxy and received an invalid response from the upstream server. This is similar to 502 HTTP Status Code.
1015 TLS handshake Reserved. Indicates that the connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can’t be verified).
1016–2999 For definition by future revisions of the WebSocket Protocol specification, and for definition by extension specifications.
3000–3999 For use by libraries, frameworks, and applications. These status codes are registered directly with IANA. The interpretation of these codes is undefined by the WebSocket protocol.
4000–4999 For private use, and thus can’t be registered. Such codes can be used by prior agreements between WebSocket applications. The interpretation of these codes is undefined by the WebSocket protocol.

后面的不想翻译,请读者自行翻译,帮你贴一个翻译传送门

正确主动关闭websocket,异常关闭处理_第1张图片

关闭监听

TS

WebSocket.onclose = (event) => {
  console.log(event.code);
};

java

    @Override
    public void onClosed(WebSocket webSocket, int code, String reason) {
        super.onClosed(webSocket, code, reason);
        // todo 根据状态码执行重连
        if(code != 1000){
        
        }
    }

你可能感兴趣的:(Java,websocket,服务器,网络协议)