javascript
class WebSocketClient {
constructor() {
this.basic_url = import.meta.env.VITE_SOCKET_URL
this.socket = null;
this.socket_open = false
this.reconnect_count = 20;
this.reconnect_current = 1;
this.reconnect_interval = 5000
this.reconnect_timer = null
this.heartbeatInterval = null;
}
static instance() {
return new WebSocketClient()
}
connect(api) {
// 创建WebSocket连接
const url = this.basic_url + api
this.socket = new WebSocket(url);
// 监听连接打开事件
this.socket.onopen = () => {
this.socket_open = true
console.log('WebSocket连接已打开!');
// this.sendHeartBeat()
};
// 监听连接关闭事件
this.socket.onclose = (event) => {
this.socket_open = false
console.log('WebSocket连接已关闭:', event);
this.reconnect_timer = setTimeout(() => {
// 超过重连次数
if (this.reconnect_current > this.reconnect_count) {
clearTimeout(this.reconnect_timer)
return
}
// 记录重连次数
this.reconnect_current++
this.reconnect(api)
}, this.reconnect_interval)
};
// 监听连接错误事件
this.socket.onerror = (error) => {
console.error('WebSocket连接错误:', error);
};
}
receive(callback) {
// 监听消息接收事件
this.socket.onmessage = (message) => {
// console.log('收到消息:', message.data);
// 在这里可以对接收到的消息进行处理
callback({ data: message.data })
};
}
sendHeartBeat() {
// 停止现有的心跳发送
clearInterval(this.heartbeatInterval);
// 发送心跳消息
this.heartbeatInterval = setInterval(() => {
if (this.socket_open) {
this.send('HeartBeat');
}
}, 5000); // 每5秒发送一次心跳消息
}
send(message) {
// 发送消息到服务器
this.socket.send(message);
}
disconnect() {
// 断开WebSocket连接
if (this.socket) {
if (this.reconnect_timer) {
clearTimeout(this.reconnect_timer)
}
this.socket.close();
console.log('WebSocket连接已关闭!');
}
}
reconnect(api) {
if (this.socket && this.socket_open) {
this.socket.close();
}
if (this.reconnect_timer) {
clearTimeout(this.reconnect_timer)
}
// 重新建立WebSocket连接
this.connect(api);
}
}
export const socketClient = (() => WebSocketClient.instance())();