后端服务器宕机或重启时,前端Vue 一直重连webSocket的解决办法:
问题重现:后盾服务重启时,前端连贯的webScoket就断了,须要刷新页面能力从新建设连贯,这样用户体验的成果不好,而且有些业务场景,比方硬件监控零碎大屏这些是不容许刷新页面的,所以须要前端发现webSocket断了,而后本人一直去发动连贯。
解决思路:在webSocket的生命周期onclose和onerror时调用重连函数,减少心跳检测。
解决方案:
创立变量
data() { return { // webSocket对象 webSocket: null, // webSocketUrl地址 webSocketUrl: null, //连贯标识 防止反复连贯 isConnect: false, //断线重连后,提早5秒从新创立WebSocket连贯 rec用来存储提早申请的代码 rec: null, // 心跳发送/返回的信息 checkMsg: {hhh: 'heartbeat'}, //每段时间发送一次心跳包 这里设置为20s timeout: 20000, //延时发送音讯对象(启动心跳新建这个对象,收到音讯后重置对象) timeoutObj: null, }}
创立webSocket连贯
//创立webSocket连贯createWebSocket() { let that = this; that.webSocket = new WebSocket(that.webSocketUrl); that.initWebsocket();}
初始化webSocket连贯
initWebsocket() { let that = this; //WebSocket连贯建设之后会调用onopen办法 that.webSocket.onopen = that.websocketonopen; //当websocket收到服务器发送的信息之后 会调用onmessage办法 that.webSocket.onmessage = that.websocketonmessage; //当websocket因为各种起因(失常或者异样)敞开之后,会调用onclose办法 that.webSocket.onclose = that.websocketclose; //当websocket因为异样起因(比方服务器部署、断网等)敞开之后,会调用onerror办法 //在onerror中须要调用reConnect办法重连服务器 that.webSocket.onerror = that.websocketonerror;}
websocketonopen函数
websocketonopen() { let that = this; console.log('open'); //连贯建设后批改标识 that.isConnect = true; // 建设连贯后开始心跳 // 因为nginx个别会设置例如60s没有传输数据就断开连接 所以要定时发送数据 that.timeoutObj = setTimeout(function() { if (that.isConnect) that.webSocket.send(that.checkMsg); }, that.timeout); }
websocketonerror函数
websocketonerror() { let that = this; console.log('error'); //连贯断开后批改标识 that.isConnect = false; //连贯谬误 须要重连 that.reConnect();}
websocketonmessage函数
websocketonmessage(e) { // 拿到数据,解决本人的业务 let that = this; console.log(e.data); //获取音讯后 重置心跳 clearTimeout(that.timeoutObj); that.timeoutObj = setTimeout(function() { if (that.isConnect) that.webSocket.send(that.checkMsg); }, that.timeout);}
websocketclose函数
websocketclose() { let that = this; console.log('close'); //连贯断开后批改标识 that.isConnect = false; //连贯谬误 须要重连 that.reConnect();}
定义重连函数
reConnect() { let that = this; console.log('尝试从新连贯'); //如果曾经连上就不在重连了 if (that.isConnect) { return; } clearTimeout(that.rec); // 提早5秒重连 防止过屡次过频繁申请重连 that.rec = setTimeout(function() { that.createWebSocket(); }, 5000);}