CloseEvent.code
下面是一个示例的WebSocket错误码表格,包括错误码、错误处理方法和错误码说明:
错误码 | 错误如何处理 | 错误码说明 |
---|---|---|
1000 | 关闭连接 | 正常关闭连接 |
1001 | 关闭连接后几秒后重连 | 终端离开或刷新页面 |
1002 | 关闭连接上报日志给开发者 | 协议错误 |
1003 | 关闭连接上报日志给开发者 | 数据类型错误 |
1005 | 关闭连接提示未知的错误几秒后重连 | 无关闭状态码 |
1006 | 关闭连接 几秒后重连 | 连接意外中断 |
1007 | 关闭连接上报日志给开发者,几秒后重连 | 非法数据 |
1008 | 关闭连接笙宝日志给开发者,几秒后重连 | 消息内容违反策略 |
1009 | 关闭连接,上报日志给开发者,几秒后重连 | 消息过大 |
1010 | 关闭连接,上报日志给开发者,几秒后重连 | 扩展协商失败 |
1011 | 关闭连接 | 服务器内部错误 |
1012-1014 | 关闭连接 | 保留未使用的错误码 |
1015 | 关闭连接 | TLS握手失败 |
- 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. |
后面的不想翻译,请读者自行翻译,帮你贴一个翻译传送门
关闭监听
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){
}
}
JavaScript (Node.js):
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:8080');
ws.on('open', () => {
// WebSocket连接成功
});
ws.on('message', (data) => {
// 处理接收到的消息
});
ws.on('close', () => {
// WebSocket连接关闭
});
ws.on('error', (error) => {
// 处理WebSocket错误
ws.close();
// 执行重连逻辑
setTimeout(() => {
const newWs = new WebSocket('ws://localhost:8080');
// ...
}, 5000);
});
Python:
import websocket
def on_message(ws, message):
# 处理接收到的消息
def on_close(ws):
# WebSocket连接关闭
def on_error(ws, error):
# 处理WebSocket错误
ws.close()
# 执行重连逻辑
time.sleep(5)
new_ws = websocket.WebSocketApp("ws://localhost:8080", on_open=on_open, on_message=on_message, on_close=on_close, on_error=on_error)
# ...
def on_open(ws):
# WebSocket连接成功
ws = websocket.WebSocketApp("ws://localhost:8080", on_open=on_open, on_message=on_message, on_close=on_close, on_error=on_error)
ws.run_forever()
Java Android:
import javax.websocket.*;
@ClientEndpoint
public class WebSocketClient {
@OnOpen
public void onOpen(Session session) {
// WebSocket连接成功
}
@OnMessage
public void onMessage(String message) {
// 处理接收到的消息
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
// WebSocket连接关闭
}
@OnError
public void onError(Session session, Throwable error) {
// 处理WebSocket错误
try {
session.close();
} catch (Exception e) {
e.printStackTrace();
}
// 执行重连逻辑
try {
Thread.sleep(5000);
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
Session newSession = container.connectToServer(WebSocketClient.class, URI.create("ws://localhost:8080"));
// ...
} catch (Exception e) {
e.printStackTrace();
}
}
}
###. C#:文章来源:https://www.toymoban.com/news/detail-794196.html
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
public class WebSocketClient {
private ClientWebSocket _client;
public async Task Connect() {
_client = new ClientWebSocket();
await _client.ConnectAsync(new Uri("ws://localhost:8080"), CancellationToken.None);
// WebSocket连接成功
// 接收消息
while (_client.State == WebSocketState.Open) {
var buffer = new ArraySegment<byte>(new byte[4096]);
WebSocketReceiveResult result = await _client.ReceiveAsync(buffer, CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Text) {
string message = Encoding.UTF8.GetString(buffer.Array, buffer.Offset, result.Count);
// 处理接收到的消息
}
}
}
public async Task Close() {
await _client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
// WebSocket连接关闭
// 执行重连逻辑
await Task.Delay(5000);
await Connect();
}
}
以下是使用Kotlin和Swift语言实现关闭WebSocket并根据异常执行重连的示例:文章来源地址https://www.toymoban.com/news/detail-794196.html
Kotlin:
import okhttp3.*
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import java.util.concurrent.TimeUnit
class WebSocketClient : WebSocketListener() {
private lateinit var webSocket: WebSocket
fun connect() {
val okHttpClient = OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.pingInterval(10, TimeUnit.SECONDS)
.build()
val request = Request.Builder()
.url("ws://localhost:8080")
.build()
webSocket = okHttpClient.newWebSocket(request, this)
}
override fun onOpen(webSocket: WebSocket, response: Response) {
// WebSocket连接成功
}
override fun onMessage(webSocket: WebSocket, text: String) {
// 处理接收到的消息
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
// WebSocket连接关闭
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
// 处理WebSocket错误
webSocket.close(1000, null)
// 执行重连逻辑
Thread.sleep(5000)
connect()
}
}
fun main() {
val client = WebSocketClient()
client.connect()
// ...
}
Swift:
import Foundation
import Starscream
class WebSocketClient: WebSocketDelegate {
private var socket: WebSocket?
func connect() {
socket = WebSocket(url: URL(string: "ws://localhost:8080")!)
socket?.delegate = self
socket?.connect()
}
func websocketDidConnect(socket: WebSocketClient) {
// WebSocket连接成功
}
func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
// 处理接收到的消息
}
func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
// WebSocket连接关闭
// 执行重连逻辑
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.connect()
}
}
func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
// 处理接收到的数据
}
}
let client = WebSocketClient()
client.connect()
// ...
到了这里,关于正确主动关闭websocket,异常关闭处理的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!