vue中使用websocket通信接收后台数据、实现消息实时通讯

前言:
项目首页有一个消息铃铛,展示对应的消息数量。项目通过新增系统通知实时接收消息数量。
在这里插入图片描述
1、直接上代码

export default {
  data() {
    return {
      badgeValue: 0, // 消息总条数
      // websocket消息推送
      ws: null, // websocket实例
      wsUrl: "", // websocket连结url
      tt: null,
      heartCheck: null,
      timeoutObj: null,
      serverTimeoutObj: null,
      timer: null, // 定时器
      lockReconnect: false,
    };
  },
  methods: {
    // 页面获取用户信息
    initPage() {
      const loginInfo = JSON.parse(localStorage.getItem("loginInfo"));
      this.wsUrl = `wss://xxxxxxxxx/api/management/wsmsg/${loginInfo.userId}`;
      window.clearTimeout(this.timeoutObj);
      window.clearTimeout(this.serverTimeoutObj);
      window.clearTimeout(this.tt);
      this.createWebSocket();
    },
    // 创建websocket
    createWebSocket() {
      try {
        this.ws = new WebSocket(this.wsUrl);
        this.initWebScoketFun();
      } catch (e) {
        this.reconnect(this.wsUrl);
      }
    },
    // websocket消息提醒
    initWebScoketFun() {
      const timeout = 30000;
      this.timeoutObj = null;
      this.serverTimeoutObj = null;
      this.heartCheck = {
        start: () => {
          this.timeoutObj && window.clearTimeout(this.timeoutObj);
          this.serverTimeoutObj &&
            window.clearTimeout(this.serverTimeoutObj);
          this.timeoutObj = setTimeout(() => {
            // 这里发送一个心跳,后端收到后,返回一个心跳消息,
            this.ws.send("1");
            this.serverTimeoutObj = setTimeout(() => {
              this.ws.close();
            }, timeout);
          }, timeout);
        },
      };
      this.ws.onclose = () => {
        console.log("链接关闭", this.wsUrl);
        this.reconnect(this.wsUrl);
      };
      this.ws.onerror = () => {
        console.log("链接失败", this.wsUrl);
        this.reconnect(this.wsUrl);
      };
      this.ws.onopen = () => {
        // 心跳检测重置
        this.heartCheck.start();
      };
      this.ws.onmessage = (event) => {
        console.log(event, "webScoket心跳链接");
        if (
          event.data != "1" &&
          event.data != "链接成功" &&
          event.data.indexOf("newAutoOpenOrder") == -1
        ) {
        //获取后台的小铃铛的数量、及重新调取列表接口
          const data = JSON.parse(event.data);
          this.badgeValue = data.msgnum;
          this.getMessageList();
        }
        // 拿到任何消息都说明当前连接是正常的
        this.heartCheck.start();
      };
    },
    // 重新链接websocket
    reconnect(url) {
      if (this.lockReconnect) {
        return;
      }
      this.lockReconnect = true;
      // 没连接上会一直重连,设置延迟避免请求过多
      this.tt && window.clearTimeout(this.tt);
      this.tt = setTimeout(() => {
        this.createWebSocket(url);
        this.lockReconnect = false;
      }, 60000);
    },
    // 获取未读消息列表
    async getMarkallread() {
      const res = await markallread(this.loginInfo.userId);
      if (res && res.code == 200) {
        this.getMessageList();
      }
    },
    // 退出登录 清空WebSocket
    logout() {
      this.ws.onclose = () => { };
      this.ws.onerror = () => { };
      this.ws.close();
      window.clearTimeout(this.timeoutObj);
      window.clearTimeout(this.serverTimeoutObj);
      this.$router.push("/login");
    },
  },

最后,大家要是有问题可以随时留言,我们一起探讨!!!

  • 1
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值