nuxt中简单使用WebSocket

**export default ({ store }, inject) => {
  let userId, ws, heartbeat;
  // 这里封装了一个实现心跳的构造函数
  // 同时传入一个回调函数给定时器执行
  function Heartbeat(func, interval = 3000) {
    // 保存定时器
    this.timer = null;
    // // 定时器间隔
    // 心跳启动
    this.start = function () {
      clearInterval(this.timer);
      this.timer = setInterval(func, interval);
    };
    // 停止
    this.stop = function () {
      clearInterval(this.timer);
    };
  }

  function WebSocketInit(id) {
    ws = new WebSocket(process.env.wsURL + "?userId=" + id)
    userId = id
    // 有新消息时触发
    ws.onmessage = function (e) {
      console.log('服务器发来消息: ', e.data);
      if (e.data == "success" || e.data == "pong") {
        console.log(e.data);
        return
      }
      const data = JSON.parse(e.data);
      store.commit("utils/SetWSMsg", data);
      if (data["noticeTitle"]) {
        if (data["noticeType"] == 4) {
          console.log(JSON.parse(data.noticeContent));
          store.commit("login/SetUserInfo", JSON.parse(data.noticeContent));
        } else {
          store.commit("login/SetNoticeCount", { systemNoticeCount: 1 });
        }
      } else {
        store.commit("login/SetNoticeCount", { interactiveNoticeCount: 1 });
      }

    };
    // 发生错误触发
    ws.onerror = function (e) {
      console.log('连接错误: ', e);
    };
    // 连接关闭触发
    ws.onclose = function (e) {
      console.log('连接中断: ', e);
      heartbeat !== undefined ? heartbeat.stop() : ''
    };
    // 在 WebSocket对象实例上追加方法
    ws.sendHeartbeat = function () {
      ws.send(JSON.stringify({ fromUserId: userId, info: "ping" }));
    };
    ws.onopen = function () {
      // 连接后立即发一条消息刷存在感【必要】
      this.send(JSON.stringify({ fromUserId: userId, info: "ping" }));
      heartbeat = new Heartbeat(ws.sendHeartbeat);
      heartbeat.start();
    };
    // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.addEventListener('beforeunload', (event) => {
      // Cancel the event as stated by the standard.
      // 添加上 会出现弹窗,不添加则会静默执行回调函数内的任务,下面同这条类似作用,只是处理兼容问题
      event.preventDefault();
      // Chrome requires returnValue to be set.
      event.returnValue = '';
      ws.close()
      heartbeat.stop();
    });
    document.addEventListener("visibilitychange", function () {
      if (document.visibilityState !== 'visible') {
        ws.close()
        heartbeat.stop();
      }
    });

  }
  //inject注入
  inject("webScoket", { WebSocketInit });

};
**
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值