class ReconnectingWebSocket {
constructor(url, options = {}) {
this.url = url;
// 重连配置
this.reconnectInterval = options.reconnectInterval || 1000; // 初始重连间隔(1秒)
this.maxReconnectInterval = options.maxReconnectInterval || 30000; // 最大重连间隔(30秒)
this.reconnectDecay = options.reconnectDecay || 1.5; // 退避倍率
this.maxReconnectAttempts = options.maxReconnectAttempts || 10; // 最大重连次数
this.jitter = options.jitter || 0.2; // 随机抖动比例(防止所有客户端同时重连)
// 状态变量
this.reconnectAttempts = 0;
this.shouldReconnect = true; // 是否应该自动重连
this.ws = null;
this.reconnectTimeout = null;
// 绑定外部事件回调
this.onopen = options.onopen || (() => {});
this.onclose = options.onclose || (() => {});
this.onmessage = options.onmessage || (() => {});
this.onerror = options.onerror || (() => {});
this.connect();
}
connect() {
this.ws = new WebSocket(this.url);
this.ws.onopen = (event) => {
console.log('WebSocket 连接成功');
this.reconnectAttempts = 0; // 连接成功,重置重连次数
this.onopen(event);
};
this.ws.onmessage = (event) => {
this.onmessage(event);
};
this.ws.onerror = (event) => {
console.error('WebSocket 发生错误:', event);
this.onerror(event);
};
this.ws.onclose = (event) => {
console.log('WebSocket 连接已断开, code:', event.code);
this.onclose(event);
// 1000 和 1001 代表正常关闭(如页面跳转、主动调用close),不需要重连
if (!this.shouldReconnect || (event.code === 1000 || event.code === 1001)) {
return;
}
// 触发自动重连逻辑
this.scheduleReconnect();
};
}
scheduleReconnect() {
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
console.error('已达到最大重连次数,放弃重连');
return;
}
// 计算带有“指数退避”和“随机抖动”的重连延迟时间
const timeout = this.reconnectInterval * Math.pow(this.reconnectDecay, this.reconnectAttempts);
const jitter = 1 - this.jitter + Math.random() * this.jitter * 2;
const delay = Math.min(timeout * jitter, this.maxReconnectInterval);
console.log(`将在 ${Math.round(delay)}ms 后尝试第 ${this.reconnectAttempts + 1} 次重连...`);
this.reconnectTimeout = setTimeout(() => {
this.reconnectAttempts++;
this.connect();
}, delay);
}
// 手动发送消息
send(data) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(data);
} else {
console.warn('WebSocket 未连接,消息发送失败');
}
}
// 手动关闭连接(不再自动重连)
close() {
this.shouldReconnect = false;
if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
if (this.ws) this.ws.close(1000, 'Client manually closed');
}
}
// ================= 使用示例 =================
// 实例化带自动重连的 WebSocket
const ws = new ReconnectingWebSocket('wss://实际网址/wss', {
reconnectInterval: 1000, // 初始间隔 1秒
maxReconnectInterval: 30000, // 最长间隔 30秒
maxReconnectAttempts: 10 // 最多尝试 10 次
});
// 监听连接成功
ws.onopen = function() {
console.log('连接建立,发送 ICCID 进行绑定...');
let iccids = ""
$('input[name="device"]:checked').each(function() {
if(iccids != ""){
iccids += "," + $(this).attr('iccid');
}else{
iccids += $(this).attr('iccid');
}
});
if(iccids != ""){
const iccidData = JSON.stringify({msg_type: 'h5', iccids: iccids});
ws.send(iccidData);
}
};
// 监听服务端消息
ws.onmessage = function(event) {
console.log('收到服务端消息:', event.data);
if(event.data){
let item = event.data
showInfo(item)
falconMark(item)
}
};
// 监听连接断开
ws.onclose = function(event) {
if (event.code !== 1000) {
console.warn('连接异常断开,等待自动重连中...');
}
};