前端封装WebSocket

近期做的一个项目需要获取到用户的实时在线人数,以及用户实时在线时间.用到了websocket,所以将websocket封装了一下

utils / socket.js

import { baseIP } from '@/utils/request.js' //baseIP  === '192.168.10.102:8080/'
var lockReconnect = false// 避免重复连接
var tt

export function WebSocketTest(userid) {
  var ws = new WebSocket(`ws://${baseIP}api/users/link_websocket/`) //api/users/link_websocket/  后端给的地址
  // const userid = localStorage.getItem('user')
  // 打开一个 web socket
  ws.onopen = function() {
    ws.send(userid)
  }
  ws.onmessage = (evt) => {
    const received_msg = evt.data // 接受返回的数据
    heartCheck.start()
    localStorage.setItem('today_online_time', JSON.parse(received_msg).today_online_time)
    if (!received_msg) {
      ws.send(userid)
    }
  }
  ws.onclose = async function() {

  }
  ws.onerror = async function(e) {
    reconnect(userid)
  }
  window.onbeforeunload = function() {
    ws.close()
  }

  function reconnect(sname) {
    if (lockReconnect) {
      return
    }
    lockReconnect = true
    // 没连接上会一直重连,设置延迟避免请求过多
    tt && clearTimeout(tt)
    tt = setTimeout(function() {
      WebSocketTest.Init(sname)
      lockReconnect = false
    }, 4000)
  }
  // 心跳检测
  var heartCheck = {
    timeout: 1000 * 60 * 3,
    timeoutObj: null,
    serverTimeoutObj: null,
    start: function() {
      var self = this
      this.timeoutObj && clearTimeout(this.timeoutObj)
      this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
      this.timeoutObj = setTimeout(function() {
      // 这里发送一个心跳,后端收到后,返回一个心跳消息,
      // onmessage拿到返回的心跳就说明连接正常

        ws.send(userid)
        self.serverTimeoutObj = setTimeout(function() {
          if (ws.readyState !== 1) {
            ws.close()
          }
        // createWebSocket();
        }, self.timeout)
      }, this.timeout)
    }
  }
}

使用

import { WebSocketTest } from '@/utils/socket'

 created() {
    const userid = localStorage.getItem('user')//用户id

    WebSocketTest(userid)
  }

你可能感兴趣的:(websocket,前端,网络协议,vue.js,javascript)