前端封装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)
  }

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值