js封装一个websocket,要求有心跳重连机制
时间: 2024-01-15 16:04:33 浏览: 97
好的,下面是一个简单的 JavaScript WebSocket 封装代码,它包含心跳重连机制:
```javascript
class WebSocketClient {
constructor(url, options = {}) {
this.url = url;
this.options = options;
this.reconnectInterval = options.reconnectInterval || 1000;
this.heartbeatInterval = options.heartbeatInterval || 5000;
this.onopen = options.onopen || function() {};
this.onmessage = options.onmessage || function() {};
this.onclose = options.onclose || function() {};
this.onerror = options.onerror || function() {};
this.connect();
}
connect() {
this.socket = new WebSocket(this.url);
this.socket.onopen = () => {
console.log('WebSocket connected');
this.onopen();
this.startHeartbeat();
};
this.socket.onmessage = (event) => {
console.log(`WebSocket message received: ${event.data}`);
this.onmessage(event);
};
this.socket.onclose = (event) => {
console.log(`WebSocket closed with code ${event.code}`);
this.onclose(event);
setTimeout(() => {
console.log('WebSocket reconnecting...');
this.connect();
}, this.reconnectInterval);
};
this.socket.onerror = (error) => {
console.error(`WebSocket error: ${error.message}`);
this.onerror(error);
};
}
send(data) {
this.socket.send(data);
}
startHeartbeat() {
this.heartbeatTimer = setInterval(() => {
if (this.socket.readyState === WebSocket.OPEN) {
this.send('ping');
}
}, this.heartbeatInterval);
}
stopHeartbeat() {
clearInterval(this.heartbeatTimer);
}
close() {
this.stopHeartbeat();
this.socket.close();
}
}
```
使用方法如下:
```javascript
const ws = new WebSocketClient('ws://localhost:8080', {
onopen: () => {
console.log('WebSocket opened');
},
onmessage: (event) => {
if (event.data === 'ping') {
console.log('WebSocket heartbeat received');
} else {
console.log(`WebSocket message received: ${event.data}`);
}
},
onclose: () => {
console.log('WebSocket closed');
},
onerror: (error) => {
console.error(`WebSocket error: ${error.message}`);
},
reconnectInterval: 1000,
heartbeatInterval: 5000,
});
// 发送消息
ws.send('hello');
// 关闭连接
ws.close();
```
该代码在创建 `WebSocketClient` 对象时会自动连接 WebSocket,并启动心跳检测。当 WebSocket 断开连接时,会自动重连。可以通过调用 `send` 方法发送消息,通过调用 `close` 方法关闭连接。
阅读全文