Newer
Older
smartwell_front_yizhuang / src / store / modules / websocket.js
import { Notification } from 'element-ui'
import router from '../../router'
import user from './user'
const websocket = {
  state: {
    wsUrl: 'ws://111.198.10.15:11304/websocket/',
    websocket: null,
    wsStatus: false, // websocket连接状态
    needRefresh: false, // 是否需要刷新数据
    needHeartbeat: true, // 是否需要开启心跳机制
    ws_timeout_timer: null, // 超时计时器
    ws_live_timer: null, // 在线计时器
    clock: 50 // 时间
  },
  mutations: {
    SET_WEBSOCKET: (state, websocket) => {
      state.websocket = websocket
    },
    SET_WS_STATUS: (state, wsStatus) => {
      state.wsStatus = wsStatus
    },
    SET_NEED_REFRESH: (state, needRefresh) => {
      state.needRefresh = needRefresh
    }
  },

  actions: {
    // 连接websocket
    initWebSocket({ commit }) {
      if (typeof (WebSocket) === 'undefined') {
        Notification({
          title: '提示',
          message: '当前浏览器无法接收实时报警信息,请使用谷歌浏览器或360浏览器极速模式!',
          type: 'warning',
          duration: 0
        })
      } else {
        // 获取token保存到vuex中的用户信息,此处仅适用于本项目,注意删除或修改
        // 实例化socket,这里我把用户名传给了后台,使后台能判断要把消息发给哪个用户,其实也可以后台直接获取用户IP来判断并推送
        const socketUrl = websocket.state.wsUrl + user.state.id
        console.log(socketUrl)
        const socket = new WebSocket(socketUrl)
        commit('SET_WEBSOCKET', socket)
        commit('SET_WS_STATUS', true)
        // 监听socket打开
        socket.onopen = function() {
          console.log('浏览器WebSocket已打开')
        }
        // 监听socket消息接收
        socket.onmessage = function(msg) {
          // 转换为json对象
          const data = JSON.parse(msg.data)
          console.log(data)
          if (data.type === 'alarm') {
            commit('SET_NEED_REFRESH', true)
            Notification({
              title: '新报警来了',
              // 这里也可以把返回信息加入到message中显示
              message: data.message,
              type: 'warning',
              onClick: () => {
                router.push({
                  path: '/overview',
                  query: { refresh: true }
                })
              }
            })
            setTimeout(function() {
              commit('SET_NEED_REFRESH', false)
            }, 2000)
          }
        }
        // 监听socket错误
        socket.onerror = function() {
          Notification({
            title: '服务器错误',
            message: '无法接收实时报警信息,请检查服务器后重新刷新页面',
            type: 'error',
            duration: 0
          })
        }
        // 监听socket关闭
        socket.onclose = function() {
          console.log('WebSocket已关闭')
          commit('SET_WS_STATUS', false)
        }
      }
    },
    startHeartBeat() {
      console.log('开启心跳发送')
      const that = this
      const socket = this.socket
      this.ws_live_timer = setTimeout(function() {
        socket.send('heartbeat')
        // 倒计时,时间超了断开连接
        that.ws_timeout_timer = setTimeout(function() {
          socket.close()
        }, that.clock)
      }, that.clock)
    }
  }
}

export default websocket