建立变量javascript
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链接java
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函数nginx
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函数web
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(); }
定义重连函数websocket
reConnect() { let that = this; console.log('尝试从新链接'); //若是已经连上就不在重连了 if (that.isConnect) { return; } clearTimeout(that.rec); // 延迟5秒重连 避免过屡次过频繁请求重连 that.rec = setTimeout(function() { that.createWebSocket(); }, 5000); }