websocket 断线重连前端
时间: 2025-07-10 13:01:44 浏览: 10
在前端实现 WebSocket 断线自动重连的机制,通常需要结合心跳检测、连接状态管理以及重连策略设计。以下是一个较为完整的方案。
### 心跳检测机制
心跳检测是通过定期向服务器发送小数据包(心跳包)来确认连接是否正常。如果服务器未响应,则认为连接断开,可以触发重连逻辑。
```javascript
function setupHeartbeat(ws, interval = 30000) {
const heartbeat = () => {
if (ws.readyState === WebSocket.OPEN) {
ws.send('ping'); // 发送心跳消息
}
};
const hearbeatInterval = setInterval(heartbeat, interval);
ws.onclose = () => {
clearInterval(hearbeatInterval); // 连接关闭时清除定时器
};
}
```
### 断线重连策略
为了保证连接的可靠性,前端应实现一个重连控制器,包括:
- **最大重连次数**
- **重连间隔时间递增(退避算法)**
- **网络状态监听**
```javascript
class WebSocketReconnect {
constructor(url, options = {}) {
this.url = url;
this.options = options;
this.reconnectAttempts = 0;
this.maxRetries = options.maxRetries || 5;
this.retryInterval = options.retryInterval || 1000;
this.ws = null;
this.connect();
}
connect() {
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
console.log('WebSocket connected');
this.reconnectAttempts = 0; // 成功连接后重置尝试次数
if (this.options.onOpen) this.options.onOpen();
};
this.ws.onmessage = (event) => {
if (this.options.onMessage) this.options.onMessage(event);
};
this.ws.onclose = (event) => {
console.log('WebSocket closed:', event.reason);
this.handleReconnect();
};
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
this.ws.close();
};
}
handleReconnect() {
if (this.reconnectAttempts >= this.maxRetries) {
console.error('Maximum retry attempts reached');
return;
}
setTimeout(() => {
console.log(`Reconnecting attempt #${this.reconnectAttempts + 1}`);
this.reconnectAttempts++;
this.connect();
}, this.retryInterval * Math.pow(2, this.reconnectAttempts)); // 指数退避
}
send(data) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(data);
} else {
console.warn('WebSocket not open. Message not sent.');
}
}
}
// 使用示例
const wsClient = new WebSocketReconnect('wss://your-websocket-url', {
maxRetries: 10,
retryInterval: 1000,
onOpen: () => {
console.log('Connection established');
},
onMessage: (event) => {
console.log('Received message:', event.data);
}
});
```
### 网络状态监听
可以通过 `navigator.onLine` 和 `window.addEventListener('online/offline')` 来监听浏览器的网络状态变化,并在网络恢复时主动尝试重连。
```javascript
window.addEventListener('offline', () => {
console.log('You are now offline');
});
window.addEventListener('online', () => {
console.log('You are back online');
if (wsClient && wsClient.ws && wsClient.ws.readyState !== WebSocket.OPEN) {
wsClient.connect();
}
});
```
### 小结
上述代码实现了以下功能:
- 建立 WebSocket 连接并维护连接状态。
- 实现心跳机制以保持连接活跃。
- 在连接断开后自动尝试重连,并采用指数退避策略避免频繁请求。
- 监听网络状态变化,在网络恢复时重新连接。
此方案适用于大多数前端项目中对 WebSocket 可靠性的增强需求[^2]。
---
阅读全文
相关推荐



















