js实现一个可以自动重链的websocket客户端

发布于:2025-02-10 ⋅ 阅读:(30) ⋅ 点赞:(0)
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();
    }

    // 连接 WebSocket
    connect() {
        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();
        };
    }

    // 重连 WebSocket
    reconnect() {

        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 次
               
            });


网站公告

今日签到

点亮在社区的每一天
去签到