js实现一个可以自动重链的websocket客户端
class WebSocketClient {constructor(url, callback, options = {}) {this.url = url; // WebSocket 服务器地址this.options = options; // 配置选项(例如重试间隔、最大重试次数等)this.retryInterval = options.retryInterval || 1000; // 重试间隔(毫秒)this.maxRetries = options.maxRetries || 5; // 最大重试次数this.retryCount = 0; // 当前重试次数this.ws = null; // WebSocket 实例this.callback = callback;this.jqdom = options.jqdom || $("#websocketdiv") //展示信息的元素this.connect();}// 连接 WebSocketconnect() {this.ws = new WebSocket(this.url);//链接超时,链接5秒就放弃链接,避免链接等待太长的时间const timeoutId = setTimeout(() => {console.log('连接超时');this.ws.close(); // 关闭连接this.ws = null;}, 5000);// 连接成功回调this.ws.onopen = () => {clearTimeout(timeoutId); // 清除超时clearTimeout(this.reconnectTimeoutId); // 清除重连this.retryCount = 0; // 重置重试次数console.log('WebSocket 连接成功');this.showInfo("WebSocket服务器连接成功"); };// 接收到消息回调this.ws.onmessage = (event) => {console.log('收到消息:', event.data);this.callback(event.data);};// 连接关闭回调this.ws.onclose = (event) => {console.log('WebSocket 连接关闭', event);this.showInfo("WebSocket服务器连接关闭", "warning");this.reconnect();};// 连接错误回调this.ws.onerror = (error) => {console.error('WebSocket 错误:', error);this.showInfo("WebSocket服务器连接错误", "danger");this.ws.close();// this.reconnect();};}// 重连 WebSocketreconnect() {if (this.maxRetries == 0 || this.retryCount < this.maxRetries) {// 如果未重连且重试次数小于最大重试次数,则进行重连,0表示无限重试this.retryCount++;console.log(`尝试重新连接... 第 ${this.retryCount} 次重试`);this.showInfo("链接失败,尝试重新连接... 第 " + this.retryCount + " 次重试", "warning");this.reconnectTimeoutId = setTimeout(() => { this.connect(); // 重新连接}, this.retryInterval);//}} else {this.showInfo("链接失败,请联系管理员", "danger");}}// 发送消息send(message) {if (this.ws && this.ws.readyState === WebSocket.OPEN) {this.ws.send(message);console.log('发送消息:', message);} else {console.warn('WebSocket 未连接,无法发送消息');}}// 关闭连接close() {if (this.ws) {this.ws.close();console.log('WebSocket 连接已关闭');this.showInfo("WebSocket 连接已关闭", "dark");}}//显示连接信息.alert-success, .alert-info, .alert-warning, .alert-danger, .alert-primary, .alert-secondary, .alert-light 或 .alert-dark showInfo(text, classname = 'success') {console.log(this.jqdom)if (this.jqdom) {var html = "<div class='alert alert-" + classname + "' role='alert'>" + text + "</div>";this.jqdom.html(html);}}
}
创建一个链接:
// 使用示例const wsClient = new WebSocketClient('ws://localhost:8080/ws', function (data) {//data转为json格式data = JSON.parse(data);//z这里用于处理从服务器获取的数据}, {retryInterval: 2000, // 重试间隔 2 秒maxRetries: 5, // 最大重试次数 3 次});