WebSocket 心跳机制

    data{
        lockReconnect:false,
        timeout: 28 * 1000,//30秒一次心跳
        timeoutObj: null,//心跳心跳倒计时
        serverTimeoutObj: null,//心跳倒计时
        timeoutnum: null,//断开 重连倒计时
    },
    beforeRouteLeave(to, form, next) {
        this.isClose = true
        this.closeWebSocket()
        next()
    },
    created() {
        window.addEventListener('beforeunload', e => this.beforeunloadFn(e))
    },
    destroyed() {
        window.removeEventListener('beforeunload', e => this.beforeunloadFn(e))
    },
    mounted() {
        this.init()  
    },
    methods: {
        reconnect () { // 重新连接
            if(this.lockReconnect) return;
            this.lockReconnect = true;
            //没连接上会一直重连,设置延迟避免请求过多
            this.timeoutnum && clearTimeout(this.timeoutnum);
            this.timeoutnum = setTimeout(() => {
                //新连接
                this.websocket.close()
                this.init();
                this.$message({
                    message: '网络异常,正在尝试重新连接',
                    type: 'warning'
                });
                this.lockReconnect = false;
            }, 5000);
        },
        reset () { // 重置心跳
            // 清除时间
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            // 重启心跳
            this.start();
        },
        start () { // 开启心跳
            this.timeoutObj && clearTimeout(this.timeoutObj);
            this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
            this.timeoutObj = setTimeout(() => {
                // 这里发送一个心跳,后端收到后,返回一个心跳消息,
                if (this.websocket && this.websocket.readyState == 1) { // 如果连接正常
                    // 开启心跳:连接正常
                    this.websocketsend('heartbeat');
                } else { // 否则重连
                    // 开启心跳:连接不正常,重连
                    this.reconnect();
                }
            }, this.timeout)
        },
        clear(){//连接断开,清空数据
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
        },
        beforeunloadFn(e) {
            this.clear()
            this.reconnect()
        },
        init(){
            if ("WebSocket" in window) {
                this.websocket = new WebSocket('ws://192.168.2.99:9001/websocket/'+this.id) //公司测试
                // this.websocket = new WebSocket('ws://192.190.10.39:9001/websocket/'+this.id) //现场
                this.initWebSocket()
            } else {
                alert("当前浏览器 Not support websocket");
            }
        },
        initWebSocket() {
            console.log('开始连接。。。')
            // 连接错误
            this.websocket.onerror = this.setErrorMessage;
            // 连接成功
            this.websocket.onopen = this.setOnopenMessage;
            // 收到消息的回调
            this.websocket.onmessage = this.setOnmessageMessage;
            // 连接关闭的回调
            this.websocket.onclose = this.setOncloseMessage;
            // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
            window.onbeforeunload = this.onbeforeunload;
        },
        setErrorMessage() {    
            //重连
            this.reconnect();
            console.log(
                "WebSocket连接发生错误   状态码:" + this.websocket.readyState
            );
        },
        setOnopenMessage() {
            //开启心跳
            this.start();
            this.$message({
                message: '连接成功',
                type: 'success'
            });
            console.log("WebSocket连接成功    状态码:" + this.websocket.readyState);
        },
        setOnmessageMessage(event) {
            let data = JSON.parse(event.data)
        },
        setOncloseMessage() {
            //重连
            if(!this.isClose){
                this.reconnect();
            }
            console.log("WebSocket连接关闭    状态码:" + this.websocket.readyState);
        },
          
        onbeforeunload () {
            this.closeWebSocket();
        },
        //websocket发送消息
        websocketsend(messsage) {
            console.log('websocket发送消息')
            this.websocket.send(messsage)
        },
        closeWebSocket() { // 关闭websocket
            this.websocket.close()
            this.clear()
        },
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值