在vue中使用websocket

本文介绍了如何在Vue应用中使用WebSocket进行设备状态轮询和控制,包括设备列表获取、关机操作、心跳保持以及数据接收处理。通过实例展示了初始化WebSocket、发送关键操作消息和维护连接的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中有需求实时更新设备状态
一中是axios轮训,隔几秒去向服务端请求
我用的是websocket,主动发送接受消息,并使用心跳包让websocket不断开一直查询设备状态

在vue中使用websocket的组件中使用

 methods: {
    //关机
    turnOff() {
      if (this.listSome) {
        if (this.selectOnline) {
          this.$confirm({
            title: "您确认关机吗",
            onOk: () => {
              console.log("发送关机指令");
              let userInfo = this.$ls.get("userInfo");
              let obj3 = {
                action: 2,
                extand: "user",
                chatMsg: {
                  senderId: userInfo.id,
                  msg: "关机",
                  msgType: 1,
                  data: { devices: [] },
                },
              };
              obj3.chatMsg.data.devices = this.checkList;
              console.log(obj3);
              this.websocket.send(JSON.stringify(obj3));
            },
          });
        } else {
          this.$message.error("您只能勾选在线的设备");
        }
      } else {
        this.$message.error("你选择你需要操作的设备");
      }
    },

    //获取设备列表
    getDeviceList() {
      this.$api.getDeviceList().then((res) => {
        if (res.success) {
          let arr = res.data.devices.map((r) => r.serialNum);
          this.list = arr;
          this.websocketsendSecond();
          this.timer2 = setTimeout(this.websocketsendThird, 2000);
        }
      });
    },
    //webscoket 初始化
    initWebSocket() {
      const wsurl = this.$globalVariable.wsurl; //ws 相当于http 而wss 相当于https
      this.websocket = new WebSocket(wsurl); //实例对象
      this.websocket.onmessage = this.websocketonmessage;
      this.websocket.onopen = this.websocketonopen;
      this.websocket.onerror = this.websocketonerror;
      this.websocket.onclose = this.websocketclose;
    },
    //连接建立
    websocketonopen() {
      console.log("前端连接建立成功");
      //连接建立之后执行send方法发送数据
      this.websocketsendFirst();
      this.getDeviceList();
      this.timer = setInterval(() => {
        this.doSend();
      }, 10 * 1000);
      this.timer1 = setInterval(() => {
        this.doSend1();
      }, 2 * 60 * 1000);
    },
    //websocket心跳  防连接超时  WebSocket规定在一定时间内没有数据交互,就会自动断开
    doSend() {
      console.log("发送心跳");
      this.websocketsendSecond();
    },
    //websocket心跳  防连接超时  WebSocket规定在一定时间内没有数据交互,就会自动断开
    doSend1() {
      console.log("发送心跳");
      this.websocketsendThird();
    },
    //首次发送数据 建立连接
    websocketsendFirst() {
      console.log("首次向后端发送数据");
      let userInfo = this.$ls.get("userInfo");
      let obj1 = {
        action: 1,
        extand: "user",
        chatMsg: {
          senderId: userInfo.id,
          receiverId: "",
          msg: "建立连接",
          msgType: 0,
        },
      };
      // console.log(JSON.stringify(obj1));
      this.websocket.send(JSON.stringify(obj1)); //发送数据,传什么数据由实际需求决定
    },
    //查看设备状态
    websocketsendSecond() {
      console.log("查询设备状态");
      let userInfo = this.$ls.get("userInfo");
      let obj2 = {
        action: 2,
        extand: "user",
        chatMsg: {
          senderId: userInfo.id,
          msg: "查询设备状态",
          msgType: 4,
          data: { devices: [] },
        },
      };
      obj2.chatMsg.data.devices = this.list;
      if (
        obj2.chatMsg.data.devices.length === this.list.length &&
        obj2.chatMsg.data.devices.length > 0
      ) {
        console.log(obj2);
        this.websocket.send(JSON.stringify(obj2));
      }
    },
    //请求桌面上传
    websocketsendThird() {
      console.log("请求桌面上传");
      let userInfo = this.$ls.get("userInfo");
      let obj2 = {
        action: 2,
        extand: "user",
        chatMsg: {
          senderId: userInfo.id,
          msg: "请求桌面上传",
          msgType: 18,
          data: { devices: [] },
        },
      };
      let arr = this.buildOptions.filter((r) => r.isOnline);
      this.buildOptions.forEach((r) => {
        if (r.isOnline) {
          obj2.chatMsg.data.devices.push(r.serialNum);
        }
      });
      if (
        obj2.chatMsg.data.devices.length === arr.length &&
        obj2.chatMsg.data.devices.length > 0
      ) {
        console.log(JSON.stringify(obj2));
        this.websocket.send(JSON.stringify(obj2));
      }
    },
    //数据接收
    websocketonmessage(e) {
      console.log("接收后端返回数据");
      var result = JSON.parse(e.data);
      console.log(result);
      if (result.msgType === 0) {
        if (result.data) {
          // console.log(result.data.devices);
          this.buildOptions = result.data.devices;
          if (this.statusForm.region == 3) {
            this.buildOptions = this.buildOptions.filter((rrr) =>
              (rrr.buildingName + rrr.classroomName).includes(this.value)
            );
          } else {
            this.buildOptions = this.buildOptions.filter((rrr) => {
              if (this.statusForm.region === 2) {
                return (
                  rrr.isOnline === null &&
                  (rrr.buildingName + rrr.classroomName).includes(this.value)
                );
              } else if (this.statusForm.region === 1) {
                return (
                  rrr.isOnline === true &&
                  (rrr.buildingName + rrr.classroomName).includes(this.value)
                );
              } else {
                return (
                  rrr.isOnline === false &&
                  (rrr.buildingName + rrr.classroomName).includes(this.value)
                );
              }
            });
          }
        }
      }
    },
    //连接建立失败重连
    websocketonerror() {
      this.initWebSocket();
    },
    //连接关闭
    websocketclose(e) {
      console.log("websocket断开连接");
      clearInterval(this.timer);
      clearInterval(this.timer1);
      clearInterval(this.timer2);
    },
  },
  //vue生命周期创建后
  created() {
    this.initWebSocket();
  },
  destroyed() {
    this.websocketclose();
  },
  //在页面离开时做的操作
  beforeRouteLeave(to, from, next) {
    this.$destroy();
    next();
  },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值