WebSocket 使用

heartCheck: {
                reconnectCount: 5,
                timeout: 50000,
                timeoutObj: null,
                serverTimeoutObj: null,
                reset: () => {
                    this.heartCheck.reconnectCount = 5;
                    if (this.heartCheck.timeoutObj)
                        clearTimeout(this.heartCheck.timeoutObj);
                    if (this.heartCheck.serverTimeoutObj)
                        clearTimeout(this.heartCheck.serverTimeoutObj);
                    console.log('reset')
                    this.heartCheck.timeoutObj = setTimeout(() => {
                        this.websoket.send("alive");
                        // 发送过去过了timeout还没接受到消息的话就断开重连
                        this.heartCheck.serverTimeoutObj = setTimeout(() => {
                            this.websoket.close();
                            this.websoketFn();//重连
                        }, this.heartCheck.timeout)
                    }, this.heartCheck.timeout)
                },
            },
// 先定义需要的数据,以及断开重连函数
websoketFn() {
            // this.websoket = new WebSocket(`wss://` + url);
            this.websoket = new WebSocket(`ws://192.168.10.183` + this.$route.query.roomId)
            console.log(this.websoket);
            
            // 开启的回调
            this.websoket.onopen = () => {
                this.heartCheck.reset();
                console.log('发送数据')
            };
            // 通信时
            this.websoket.onmessage = (event) => {
                // 重置之前的心跳
                this.heartCheck.reset();
                console.log('数据已接收...');
                
            };
            this.websoket.onerror = (event) => {
                this.heartCheck.reconnectCount--;
                if (this.heartCheck.reconnectCount > 0) {
                    setTimeout(() => {
                        this.websoketFn();//重连
                    }, 2000)
                } else {
                    console.log('链接出错');
                    
                }
            };
            this.websoket.onclose = () => {
                if (this.heartCheck.timeoutObj)
                    clearTimeout(this.heartCheck.timeoutObj);
                if (this.heartCheck.serverTimeoutObj)
                    clearTimeout(this.heartCheck.serverTimeoutObj);
                    console.log("连接已关闭");
            };
        },

猜你喜欢

转载自www.cnblogs.com/baifubin/p/11308007.html