websocket断开后自动重连需监听onclose和onerror事件,手动重建连接并采用指数退避策略(初始1秒,上限30秒)、随机抖动及状态标识(如ismanuallyclosed)防止误重连。

WebSocket 断开后自动重连,核心是监听 onclose 和 onerror 事件,在合适时机调用 new WebSocket() 重建连接,并控制重连频率避免雪崩。
监听断开与错误,触发重连逻辑
WebSocket 实例本身不提供“重连”方法,需手动重建。关键是在 onclose(正常或异常断开)和 onerror(连接失败、协议错误等)中启动重连流程:
-
onclose会传入event.code和event.reason,可据此判断是否值得重连(如1000是主动关闭,通常不重连;1006是连接异常,应重连) -
onerror一般不带详细原因,但表示连接未建立成功或底层出错,也应纳入重连条件 - 注意:不要在
onopen中清除重连定时器以外的逻辑,否则可能干扰状态管理
实现指数退避重连,避免频繁请求
连续快速重连不仅浪费资源,还可能被服务端限流。推荐使用指数退避(Exponential Backoff)策略:
- 初始延迟 1 秒,失败后翻倍(1s → 2s → 4s → 8s…),上限建议设为 30 秒或 60 秒
- 每次重连前清空上一次的定时器,防止多个重连任务并发
- 可加入随机抖动(如 ±20%),缓解多客户端同时重连造成的峰值压力
管理连接状态与重连标识
防止重复连接或误重连,需要明确的状态标记:
- 用一个布尔值(如
isConnecting或reconnecting)标识当前是否处于连接/重连中 - 在
onopen中置为false,在开始重连前置为true - 用户主动调用
ws.close()时,应设置标志位(如manualClose = true),并在onclose中跳过重连 - 可配合
ws.readyState辅助判断,但注意它在onclose触发时已变为CLOSED (3)
封装成可复用的类(精简示例)
以下是一个轻量级自动重连 WebSocket 封装参考:
class ReconnectWebSocket {
constructor(url, options = {}) {
this.url = url;
this.maxReconnectDelay = options.maxDelay ?? 30000;
this.minReconnectDelay = options.minDelay ?? 1000;
this.reconnectDelay = this.minReconnectDelay;
this.reconnectTimer = null;
this.ws = null;
this.isManuallyClosed = false;
this.connect();
}
<p>connect() {
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
console.log('WebSocket connected');
this.reconnectDelay = this.minReconnectDelay; // 成功后重置延迟
this.isManuallyClosed = false;
};
this.ws.onclose = (event) => {
if (this.isManuallyClosed) return;
if (event.code === 1000) return; // 正常关闭不重连
this.reconnect();
};
this.ws.onerror = () => {
if (this.isManuallyClosed) return;
this.reconnect();
};
}</p><p>reconnect() {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = setTimeout(() => {
console.log(<code>Reconnecting... (delay: ${this.reconnectDelay}ms)</code>);
this.connect();
this.reconnectDelay = Math.min(
this.reconnectDelay <em> 2,
this.maxReconnectDelay
);
}, this.reconnectDelay + Math.random() </em> 200 - 100); // 加抖动
}</p><p>close() {
this.isManuallyClosed = true;
if (this.ws) this.ws.close();
clearTimeout(this.reconnectTimer);
}</p><p>send(...args) {
return this.ws?.send(...args);
}
}</p>使用:const ws = new ReconnectWebSocket('wss://example.com');,调用 ws.close() 可终止重连。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











