关于使用class 对webSocket 进行优化封装

本人针对上一篇的webSocket 的封装分析 以及查看了打印的情况 进行二次封装并且 增加 处理函数

  本封装包含维持心跳处理 heartBeat 函数
  首次连接消息处理 位置 onOpen 
  断掉重连处理 位置 onClose

  后期会对webSocket class 的构造函数配置进行结构优化!从而达到代码阅读的便捷性 以及 使用实例的方便性

class UseWebSocket {
    constructor(
        wsObject = {
            url: null,
            is_reonnect: true, // 是否自动重连
            reconnect_count: 3, //可以重连的次数
            reconnect_interval: 3000, //重连频率
            hearbeat_interval: 5000, // 心跳发送频率
        }, // 用于初始化配置的对象
        onMessage,// 回调函数
       
        ws = null,
        reconnect_current = 0,
        reconnect_timer = null,
        socket_open = false,
        hearbeat_timer = null,
        is_reonnect = true,
        reconnect_interval = null,
        hearbeat_interval = null,
        reconnect_count = 3

    ) {
        this.wsObject = wsObject;
        this.ws = ws; // ws返回的对象

        // 重连次数
        this.reconnect_count = reconnect_count;
        // 当前重连次数
        this.reconnect_current = reconnect_current;
        // 重连timer
        this.reconnect_timer = reconnect_timer;
        // 重连频率
        this.reconnect_interval = reconnect_interval;
        // 是否自动重连
        this.is_reonnect = is_reonnect;
        // 开启标识
        this.socket_open = socket_open;
        // 心跳timer
        this.hearbeat_timer = hearbeat_timer;
        // 心跳发送频率
        this.hearbeat_interval = hearbeat_interval;
        this.onMessage = onMessage;
    }
    // 初始化
    initSocket() {
        if (!("WebSocket" in window)) {
            console.log("浏览器不支持WebSocket");
            return null;
        }
        // 对象存在不需要连接
        if (this.ws) {
            return this.ws;
        }

        this.objInit()

        //  websocket对象赋值
        this.ws = new WebSocket(this.wsObject.url);

        // websocket 断开
        this.ws.onclose = (e) => {

            clearInterval(this.hearbeat_timer);
            this.socket_open = false;
            // 断开重连的处理 查看是否主动断开 来进行重连
            if (this.is_reonnect) {
                // 确立this 指向
                let _this = this;

                this.reconnect_timer = setTimeout(() => {
                    // 超过重连次数
                    if (_this.reconnect_current > _this.reconnect_count) {
                        clearTimeout(_this.reconnect_timer);
                        // 释放对象
                        _this.ws = null;
                        return;
                    }
                    // 记录重连次数
                    _this.reconnect_current++;

                    _this.reconnect();
                }, this.reconnect_interval);
            }
        };


        this.ws.onerror = (e) => {
            // console.log("webSocket error WebSocket连接发生错误", e);
        };

        // 消息处理
        this.ws.onmessage = (e) => {
            var params = JSON.parse(e.data);
            console.log("webSocket message", params);
            if (this.onMessage) {
                this.messageReceive(params, this.onMessage);
            }
        };

        this.ws.onopen = (e) => {
            console.log(
                "webSocket open 连接成功",
                e
            );

            if (this.reconnect_current == 0) {
                let data = {
                    kind: 1, //请求类型 kind 1 首次连接开启
                    kindString: "socketStart",
                };

                this.sendMsg(data);
            }

            clearTimeout(this.reconnect_timer);

            this.reconnect_current = 0;
            this.socket_open = true;
            this.is_reonnect = true;
            this.heartbeat();
        };
    }
    // 数值赋值初始化
    objInit() {
        this.reconnect_count = this.wsObject.reconnect_count ? this.wsObject.reconnect_count : 3;
        this.is_reonnect = this.wsObject.is_reonnect ? this.wsObject.is_reonnect : true;
        this.reconnect_interval = this.wsObject.reconnect_interval ? this.wsObject.reconnect_interval : 3000;
        this.hearbeat_interval = this.wsObject.hearbeat_interval ? this.wsObject.hearbeat_interval : 5000;
    }

    messageReceive(e, onMessage) {
        onMessage(e);
    }

    // 发送消息
    sendMsg(data, callback = null) {
        //已开启
        // console.log("执行发送", data);
        if (this.ws.readyState == this.ws.OPEN) {

            this.ws.send(JSON.stringify(data));

            if (callback) {
                callback();
            }

        }
    }

    // 维持心跳
    heartbeat() {
        if (this.hearbeat_timer) {
            clearInterval(this.hearbeat_timer);
        }

        let _this = this;

        this.hearbeat_timer = setInterval(() => {
            var data = {
                kind: 0, //请求类型 kind 0 心跳包
                kindString: "heartBeat",
            };
            //   console.log("里面==》", _this, JSON.stringify(data));
            _this.sendMsg(data);
        }, this.hearbeat_interval);
    }
    // 重连
    reconnect() {
        if (this.ws && this.socket_open) {
            this.ws.close();
        }

        this.ws = null;
        // console.log("执行重连===>", this);
        this.initSocket();
    }

    destory() {
        if (this.ws != null && this.ws.readyState == this.ws.OPEN) {
            clearInterval(this.hearbeat_interval);
            this.is_reonnect = false;
            this.ws.close();

        }
        // 释放对象
        this.ws = null;
    }
}

 对引用实例进行展示

const onMessage = (e) => {
  console.log("消息返回结果===》", e);
};
// let wsObj = new UseWebsocket(
//   `/ws/stream/online?app_id=1752175006404976642&uid=${uid}`,
//   onMessage
// );
let wsObj = new UseWebsocket(
  `/ws/stream/online?app_id=1731632683577503746&uid=${uid}`,
  onMessage
);

wsObj.initSocket();

相对于上一版本 消除当时处理onClose时的重连bug 以及新增onMessage的消息处理

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值