标签:timeoutObj vue websocket mydata self 笔记 var ws 心跳
data () { return { ws: null,//建立的连接 lockReconnect: false,//是否真正建立连接 timeout: 28*1000,//30秒一次心跳 timeoutObj: null,//心跳心跳倒计时 serverTimeoutObj: null,//心跳倒计时 timeoutnum: null,//断开 重连倒计时 } }, created() { this.initWebpack(); }, methods: { initWebpack(){ this.ws = new WebSocket(process.env.SOCKET_OTC); this.ws.onopen = this.onopen; this.ws.onmessage = this.onmessage; this.ws.onclose = this.onclose; this.ws.onerror = this.onerror; }, reconnect() {//重新连接 var that = this; if(that.lockReconnect) { return; }; that.lockReconnect = true; //没连接上会一直重连,设置延迟避免请求过多 that.timeoutnum && clearTimeout(that.timeoutnum); that.timeoutnum = setTimeout(function () { //新连接 that.initWebpack(); that.lockReconnect = false; },5000); }, reset(){//重置心跳 var that = this; //清除时间 clearTimeout(that.timeoutObj); clearTimeout(that.serverTimeoutObj); //重启心跳 that.start(); }, start(){//开启心跳 var self = this; self.timeoutObj && clearTimeout(self.timeoutObj); self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj); self.timeoutObj = setTimeout(function(){ //这里发送一个心跳,后端收到后,返回一个心跳消息, if (self.ws.readyState == 1) {//如果连接正常 self.ws.send("heartCheck"); }else{//否则重连 self.reconnect(); } self.serverTimeoutObj = setTimeout(function() { //超时关闭 self.ws.close(); }, self.timeout); }, self.timeout) }, onopen() { var msg = JSON.stringify({cmd: 'enter_chatting', token:this.COOKIE.getCookie("token")}); this.ws.send(msg); console.log("open"); this.getNoReadRecords(); //开启心跳 this.start(); }, onmessage(e) { this.mydata = JSON.parse(e.data); if(this.mydata.fromID == this.states.customerId){ this.mydata.chatType = 2; }else{ this.mydata.chatType = 1; } var content =this.getContentTypes(this.mydata.content,this.mydata.chatType); this.records.push(this.mydata); //收到服务器信息,心跳重置 this.reset(); }, onclose(e) { console.log("连接关闭"); console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean); var msg = JSON.stringify({cmd: 'out_chatting', token:this.COOKIE.getCookie("token")}); this.ws.send(msg); //重连 this.reconnect(); }, one rror(e) { console.log("出现错误"); //重连 this.reconnect(); } }
标签:timeoutObj,vue,websocket,mydata,self,笔记,var,ws,心跳 来源: https://www.cnblogs.com/mybug/p/11718549.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。