H5即時通信Websocket

/**
 * 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
相關文章
相關標籤/搜索