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("连接已关闭"); }; },
// 简易版 initWebSocket(){ //初始化weosocket const wsuri = `ws://192.168.10.182/` + this.$route.query.roomId this.websock = new WebSocket(wsuri); this.websock.onmessage = this.websocketonmessage() this.websock.onopen = this.websocketonopen() this.websock.onerror = this.websocketonerror() this.websock.onclose = this.websocketclose() }, websocketonopen(){ //连接建立之后执行send方法发送数据 let actions = {"type":0,"liveStudioId":this.$route.query.roomId,"userId": sessionStorage.getItem('userId'),"userName": sessionStorage.getItem('nickname'),"msg":'1111'} this.websocketsend(JSON.stringify(actions)) }, websocketonerror(){//连接建立失败重连 this.heartCheck.reconnectCount--; if (this.heartCheck.reconnectCount > 0) { setTimeout(() => { this.initWebSocket();//重连 }, 2000) } else { console.log('链接出错'); } }, websocketonmessage(e){ //数据接收 this.heartCheck.reset(); console.log('数据已接收...'); }, websocketsend(Data){//数据发送 this.websock.send(Data); }, websocketclose(e){ //关闭 if (this.heartCheck.timeoutObj) { clearTimeout(this.heartCheck.timeoutObj) if (this.heartCheck.serverTimeoutObj) { clearTimeout(this.heartCheck.serverTimeoutObj) console.log("连接已关闭") } } },