解决后台服务重启后前端webSocket断开连接,需要刷新页面重新建立连接,用户体验效果不好,部分业务场景,如大硬件监控系统的screen,不允许刷新页面,所以前端需要发现webSocket坏了,然后自己继续发起连接。解决方法:在webSocket生命周期的onclose和onerror期间调用重连函数,并添加心跳检测。解决方法:创建变量data(){return{//webSocket对象webSocket:null,//webSocketUrl地址webSocketUrl:null,//连接标识,避免重复连接isConnect:false,//断开重连后,延迟重连5秒创建WebSocket连接rec,存放延迟请求的代码rec:null,//心跳发送/返回信息checkMsg:{hhh:'heartbeat'},//每次发送一个心跳包,这里设置为20stimeout:20000,//延迟发送消息对象(启动心跳创建此对象,收到消息后重置对象)timeoutObj:null,}}创建webSocket连接//创建webSocket连接createWebSocket(){letthat=this;that.webSocket=newWebSocket(that.webSocketUrl);that.initWebsocket();}初始化webSocket连接initWebsocket(){letthat=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;}websocketonopenfunctionwebsocketonopen(){letthat=this;console.log('打开');//修改标识那个。是连接=真;//建立连接后开始心跳//因为nginx一般会设置比如60s断开连接不传输数据,所以需要定时发送数据that.timeoutObj=setTimeout(function(){if(that.isConnect)that.webSocket.send(that.checkMsg);},that.timeout);}websocketonerror函数websocketonerror(){letthat=this;console.log('错误');//连接断开后修改标识that.isConnect=false;//连接错误需要重连that.reConnect();}websocketonmessagefunctionwebsocketonmessage(e){//获取数据处理自己的业务letthat=this;控制台日志(e.data);//获取resetheartbeatcl后的消息earTimeout(that.timeoutObj);that.timeoutObj=setTimeout(function(){if(that.isConnect)that.webSocket.send(that.checkMsg);},that.timeout);}websocketclosefunctionwebsocketclose(){letthat=this;console.log('关闭');//连接断开后修改标识that.isConnect=false;//连接错误需要重连that.reConnect();}定义重连函数reConnect(){letthat=this;console.log('尝试重连');//如果已经连接,则不会重连if(that.isConnect){return;}clearTimeout(that.rec);//延迟5秒避免重连请求重连太多that.rec=setTimeout(function(){that.createWebSocket();},5000);}
