/** * Created by admin on 2017/8/19. */ // import Vue from 'vue' // import axios from './HTTP.js' // Vue.use(axios) import * as DB from './DBDATA.js' // import qs from 'qs' const WebSocketMsg = function (_self, url) { let obj = {} obj.infoData = DB.INFO_DATA obj.ws = null obj.lockReconnect = false // 避免重復連接 // obj.wsUrl = 'ws://192.168.1.90:8080/service-jcj/websocket' // 通訊地址 obj.createWebSocket = function () { // 通訊開啟事件 try { obj.ws = new WebSocket(url) obj.initEventHandle() } catch (e) { obj.reconnect(url) } } obj.initEventHandle = function () { // 通訊操作事件 開啟 消息 關閉 錯誤 obj.ws.onclose = function () { obj.reconnect(url) // 通訊重連 console.log('通訊關閉') } obj.ws.onerror = function () { obj.reconnect(url) // 通訊重連 console.log('通訊錯誤') } obj.ws.onopen = function () { // 心跳檢測重置 obj.heartCheck.reset() // 心跳檢測重置 obj.heartCheck.start() // 心跳檢測開啟 console.log('通訊開啟') } obj.ws.onmessage = function (event) { // 如果獲取到消息,心跳檢測重置 // 拿到任何消息都說明當前連接是正常的 obj.heartCheck.reset() // 心跳檢測重置 obj.heartCheck.start() // 心跳檢測開啟 console.log('通訊消息') console.log(event) } } obj.reconnect = function () { // 通訊重連 if (obj.lockReconnect) { // 如果為真 結束事件 為假 執行后續事件 return } obj.lockReconnect = true // 沒連接上會一直重連,設置延遲避免請求過多 setTimeout(function () { obj.createWebSocket(url) // 新開啟通訊 obj.lockReconnect = false }, 2000) } // 心跳檢測 obj.heartCheck = { timeout: 6000, // 60秒 timeoutObj: null, serverTimeoutObj: null, reset: function () { clearTimeout(this.timeoutObj) clearTimeout(this.serverTimeoutObj) return this }, start: function () { let that = this that.timeoutObj = setTimeout(function () { // 這里發送一個心跳,后端收到后,返回一個心跳消息, // onmessage拿到返回的心跳就說明連接正常 obj.ws.send('@') // 向后端發送消息 如果后端接收 則重置心跳 that.serverTimeoutObj = setTimeout(function () { // 如果超過一定時間還沒重置,說明后端主動斷開了 obj.ws.close() // 如果onclose會執行reconnect,我們執行ws.close()就行了.如果直接執行reconnect 會觸發onclose導致重連兩次 }, that.timeout) }, that.timeout) } } return obj } export default WebSocketMsg