websocket心跳和重连机制websocket是前后端之间的长连接,前后端也可能因为某些情况而失效,它们之间没有反馈提醒。因此,为了保证连接的连续性和稳定性,websocket心跳重连应运而生。使用原生websocket时,如果设备网络断开,不会立即触发websocket事件,前端不知道当前连接是否已经断开。这时候如果调用了websocket.send方法,浏览器会发现链接断开了,会立即或者一定时间后触发onclose函数(不同的浏览器或者浏览器版本可能表现不同)。后端websocket服务也可能出现异常,导致连接断开。此时前端还没有收到断线通知,所以前端需要定时发送心跳消息ping。前端连接没问题。如果一定时间内没有收到pong报文,说明连接不正常,前端会进行重连。心跳机制心跳机制就是每隔一段时间向服务器发送一个数据包,告诉服务器它还活着,同时客户端会确认服务器是否还活着。如果它还活着,它会返回一个数据包给客户端。确保服务器还活着,否则可能会断网,需要重连。当连接建立成功后,就会开始检测心跳。大致流程如下:exportdefault{name:'App',data(){return{isOpen:false,//是否连接pingIntervalSeconds:3000,//心跳连接时间lockReconnect:false,//是否连接真建立heartTimer:null,//心跳定时器serverTimer:null,//服务器超时定时器reconnectTimer:null,//断开重连倒计时sendFixHeartTimer:null,//20s固定发送心跳计时}},created(){this.connect();},methods:{//ws连接connect(){ws.WebSocket('wss://ws.51vv.com/game','');//监听连接打开,ws.onopen(e=>{//开始心跳this.start();this.sendFixHeart();});ws.onmessage(e=>{//接收服务器消息,心跳复位,上报this.reset();});ws.onerror(e=>{//重新连接this.reconnect();});ws.onclose(e=>{//重新连接这个。重新连接();});},//启动心跳start(){this.heartTimer&&clearTimeout(this.heartTimer);this.serverTimer&&clearTimeout(this.serverTimer);this.heartTimer=setTimeout(()=>{this.send({cmd:1100,});//超时关闭,超时时间5sthis.serverTimer=setTimeout(()=>{ws.close();},5000);},this.pingIntervalSeconds)},//在3000-5000之间重连,设置延迟,避免请求过多reconnect(){//设置lockReconnect变量,避免重复连接if(this.lockReconnect)return;this.lockReconnect=true;this.reconnectTimer&&clearTimeout(this.reconnectTimer);this.reconnectTimer=setTimeout(()=>{this.connect();this.lockReconnect=false;},parseInt(Math.random()*2000+3000));},//重置心跳reset(){clearTimeout(this.heartTimer);clearTimeout(this.serverTimer);这个。开始();},//20s固定发送心跳sendFixHeart(){clearInterval(this.sendFixHeartTimer);this.sendFixHeartTimer=setInterval(()=>{this.send({cmd:1100,});},20000);}}}当客户端发起心跳,网页关闭时,会主动触发服务器事件onclose手动断开连接,网络会触发客户端onerror。再次打开网络时,不会触发客户端的onclose和onerror事件。(需要监控网络情况,有网络时重新连接。)当开发者工具断网时,客户端onclose和onerror会触发一个长时间的事件,当再次打开网络时,客户端oncloseonerror事件也会被触发。电梯断线总会触发客户端onerror事件~~~~2.服务器发起心跳
