建立變量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); }