socket.js 2.3 KB
import store from '../store'
import axios from './http'
import * as API from './api'

window.PushWs = null;
window.pushwsurl = null;
window.pushwsClock = null;
var sessionID = ''
export const pushws = function getpushws() {
  let userName = localStorage.getItem("user_id");
  let clientTimer = new Date().getTime();
  sessionID = clientTimer;
  axios.get(API.url + "/manage/push/ws_url?src_type=user&user_unid=" + userName + "&client_unid=" + clientTimer,{
    headers: {
      'authorization': localStorage.getItem('atoken')
    }
  })
    .then(response => {
      openWs("pushws", response.data.ws_url);
      pushwsurl =  response.data.ws_url;
    });
}


function openWs(wstype, wsUrl) {
  if ("WebSocket" in window) {
    if (wstype == "pushws") PushWs = new WebSocket(wsUrl);
  } else if ("MozWebSocket" in window) {
    if (wstype == "pushws") PushWs = new MozWebSocket(wsUrl);
  } else {
    if (wstype == "pushws") PushWs = new SockJS(wsUrl);
  }
  /**
   * 报警推送
   */
  try {
    PushWs.onerror = function (event) {
      console.log("推送WebSocket:发生错误 ");
      console.log("错误" + event);
    };
    PushWs.onclosed = function () {
      getpushws();
      console.log("推送服务ws关闭")
    };
    PushWs.onopen = function (event) {
      debugger
      console.log("推送WebSocket:已连接");
      store.commit('setsessionID',sessionID)
      pushwsClock = setInterval(wsPushclock, 20000);
    };
    /**
     * 处理接收到的数据
     * @param {*} event
     */
    PushWs.onmessage = function (event) {
      var data = JSON.parse(event.data);
      store.dispatch("GetAlarmData", data)
      if (data.command == "post /wsapi/v1/event/black_face_events") {
      }
    }
  } catch (err) {
    console.log(err);
  }



   /**
   * 推送心跳
   */
  function wsPushclock(command) {
    let date = new Date();
    let datatimes = date.getTime();
    if (PushWs.readyState == 1) {
      try {
        let PushMessage = {
          type: "request",
          id: datatimes + 1,
          command: "get /wsapi/v1/dtid/" + pushwsurl.split('connects/')[1] + "/keep_alive", //推送服务
          mts: datatimes
        };
        PushWs.send(JSON.stringify(PushMessage));

      } catch (err) {
        console.log(err);
      }
    } else {
      clearInterval(pushwsClock);
      pushws();
    }
  }
}