web接收websocket

发布时间 2023-06-08 17:36:31作者: 大云之下
  data() {
    return {
      websock: null,
      wsuri: "ws://192.168.2.22:8025/test/fff", //WebSocket的后台地址
      actiones: { ssid: "fff" }, //传入后台的数据
    };
  },

created() {
    this.initWebSocket(); //开启WebSocket
  },
  destroyed() {
    this.websock.close(); //离开路由之后断开websocket连接
  },
methods: {
    initWebSocket() {
      //初始化weosocket
      const wsuri = this.wsuri;
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    //连接建立之后执行send方法发送数据
    websocketonopen() {
      if (this.actiones) {
        //data下的actiones属性有值就会调用,把值传入后台
        this.websocketsend(JSON.stringify(this.actiones));
      }
    },
    //连接建立失败重连
    websocketonerror() {
      this.initWebSocket();
    },
    //数据接收
    websocketonmessage(e) {
      //  const redata = JSON.parse(e.data);
      console.log(e);
    },
    //数据发送
    websocketsend(Data) {
      this.websock.send(Data);
    },
    //关闭 websocket
    websocketclose(e) {
      console.log("断开连接", e);
    },
  },