1. 为什么叫心跳包呢?
它就像心跳一样每隔固定的时间发一次,来告诉服务器,我还活着。
2. 什么是心跳机制?
1、心跳机制是每隔一段时间会向服务器发送一个数据包:告诉服务器(后台)自己还活着,同时客户端(浏览器)会确认服务器端是否还活着
2、如果还活着的话,就会回传一个数据包给客户端
3、服务端断开连接了。客户端需要重连~
3.具体实现方法
//在data中声明变量 timeout: 1000, // 30s timeoutObj: null,
//具体流程 // 判断是否已连接 initScokets() { let that = this; uni.connectSocket({ url: wsUrl + "/paperless-office/sereenSocket/" + this.meetInfo.PersonnelId, success(res) { console.log("正在连接WebSocket.... connectSocket=", res); that.open(); //1、判断是否打开连接 that.scoketMessage(); //2、判断websocket服务器是否返回信息 that.TimeOut(); //3、websocket超时操作 }, fail(err) { console.log("WebSocket连接失败 connectSocket=", err); that.error(); }, }); }, //连接成功 open() { let that = this; uni.onSocketopen((res) => { console.log("WebSocket连接成功...."); that.reset(); //连接成功之后做两秒的一次连接(心跳机制) }); }, //服务器返回信息 scoketMessage() { let that = this; uni.onSocketMessage(function (res) {
//获取服务器返回内容,并获取当前时间戳以作服务器超时判断 console.log("收到服务器内容:" + res.data); that.serveTime = new Date().getTime();
//以下可以写服务器返回之后具体操作 }); }, //超时响应 TimeOut() { let that = this; setInterval(function () { let times = new Date().getTime(); if (times - that.serveTime > 2000) { //以下做超时后的操作 } }, 500); }, // 连接失败 error() { let that = this; uni.onSocketError(function (res) { console.log("WebSocket连接打开失败,请检查!"); that.initScokets(); //连接失败之后,重新向服务器发起连接 }); }, // 心跳响应 reset() { let that = this; clearInterval(that.timeoutObj); that.timeoutObj = setInterval(function () { //做一个判断:在没有获取某个值货值其他需求下,做个无响应的websocket连接。否则就做一个有响应的连接 uni.$on("screenObj", (res) => { that.transferValue = res; console.log(that.transferValue); }); if ( that.transferValue == {} || that.transferValue == undefined || that.transferValue == null ) { that.startSend(); } else { uni.sendSocketMessage({ data: `{"event":"pushStatus","tpid":"${that.transferValue.tipId}"}`, //data值根据实际需求赋值 success: (res) => { console.log("正在发送...."); }, fail: (err) => { console.log("发送失败,重新连接...."); that.initScokets(); }, }); } // 结束同屏 uni.$on("cancelsObj", (res) => { that.consoleValue = res; console.log(that.consoleValue); if ( that.consoleValue !== {} || that.consoleValue !== undefined || that.consoleValue !== null ) { that.startSend(); } }); }, this.timeout); },
//发送信息 startSend() { uni.sendSocketMessage({ data: "{}", //data值根据实际需求赋值 success: (res) => { console.log("WebSocket连接中...."); }, fail: (err) => { console.log("发送失败,重新连接...."); }, }); },
注:以下操作根据项目需求操作,我这里做的是传值的一个判断。
uni.$on("screenObj", (res) => {
that.transferValue = res; console.log(that.transferValue);
});
if ( that.transferValue == {} || that.transferValue == undefined || that.transferValue == null ) ){}