通过监听 websocket 的 close 事件并在回调中调用 open 方法即可实现断线自动重连。具体做法是封装一个连接函数,在 onclose 中设置定时器延迟几秒后重新执行该函数,同时利用 onerror 和 onopen 分别处理异常和重置状态。

WebSocket 对象如何触发重连逻辑
当网络波动或服务器关闭连接时,浏览器会触发 onclose 事件,此时需要判断是否应该重连。如果连接非正常关闭(例如代码未主动调用 close()),则启动重连机制;若为正常关闭,则停止重连尝试。

const ws = new WebSocket('ws://localhost:8080');
let reconnectTimer = null;
ws.onclose = (event) => {
if (!event.wasClean) {
console.log('Connection closed unexpectedly, reconnecting...');
reconnectTimer = setTimeout(() => {
ws.open(); // Note: In standard JS, you usually re-instantiate or use a wrapper.
// For this example, we assume a wrapper or re-creation logic.
}, 3000);
}
};
// Better approach with re-creation:
function connect() {
const socket = new WebSocket('ws://localhost:8080');
socket.onclose = () => {
setTimeout(connect, 3000); // Reconnect after 3 seconds
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
};
return socket;
}
const wsInstance = connect();上述代码展示了最基础的自动重连模式:每次断开后等待 3 秒重新创建新的 WebSocket 实例。这种方式简单有效,但需要注意避免频繁重连导致服务器压力过大。
立即学习“Java免费学习笔记(深入)”;
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
如何防止重连风暴并管理连接状态
在实际应用中,直接无限重试可能导致“重连风暴”,即客户端在短时间内发起大量连接请求。因此需要引入指数退避策略或最大重试次数限制,并通过 readyState 属性确保当前连接处于空闲状态时才发起新连接。

class ReliableWebSocket {
constructor(url) {
this.url = url;
this.ws = null;
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 5;
this.baseDelay = 1000;
}
connect() {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
return;
}
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
this.reconnectAttempts = 0; // Reset attempts on successful connection
console.log('Connected');
};
this.ws.onclose = (event) => {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
const delay = Math.min(this.baseDelay * Math.pow(2, this.reconnectAttempts), 10000);
this.reconnectAttempts++;
console.log(`Reconnecting in ${delay}ms (Attempt ${this.reconnectAttempts})`);
setTimeout(() => this.connect(), delay);
} else {
console.error('Max reconnect attempts reached.');
}
};
this.ws.onerror = (error) => {
console.error('Error:', error);
};
}
send(data) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(data));
} else {
console.warn('WebSocket is not open. Message dropped.');
}
}
}
const client = new ReliableWebSocket('ws://localhost:8080');
client.connect();该示例引入了指数退避算法,每次重连间隔翻倍,上限为 10 秒,最多重试 5 次。这能有效缓解网络抖动带来的冲击,同时保证在恢复后能快速重连。
基于 reconnectAttempts 达到上限时的具体行为是什么
当 reconnectAttempts 达到预设的 maxReconnectAttempts 值(如 5)时,程序将不再自动发起重连请求,而是记录错误日志并终止重连循环。此时应用需依赖外部干预(如用户刷新页面或手动触发重连)来恢复连接。

















