美文网首页
vue中长链接(weosocket)使用方法

vue中长链接(weosocket)使用方法

作者: Henry01 | 来源:发表于2021-06-10 11:29 被阅读0次

1,在 created 中:

created() {
     this.initWebSocket();
      if (this.websock) {   // 关闭websocket连接
          this.websock.close();
        }
},

2,在 methods 中:

//------------------------------初始化weosocket-------------------------
    initWebSocket() {
      if (typeof WebSocket === "undefined") {
        this.$message({
          message: "您的浏览器不支持WebSocket",
          type: "warning",
        });
        return false;
      }
      const wsuri = 'ws://192.168.1.88:8080/weosocket’; // websocket地址
      this.websock = new WebSocket(wsuri);
      this.websock.onopen = this.websocketonopen;
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    //连接成功
    websocketonopen() {
      console.log("WebSocket连接成功");
      // 添加心跳检测,每3秒发一次数据,防止连接断开(跟服务器设置有关,如果服务器没有设置每隔多长时间不发消息断开,可以不进行心跳设置)
      let self = this;
      this.timer = setInterval(() => {
        try {
          //self.websock.send('test');
          console.log("发送消息");
        } catch (err) {
          console.log("断开了:" + err);
          self.connection();
        }
      }, 30000);
    },
    //接收后端返回的数据
    websocketonmessage(e) {
      let data1Json = JSON.parse(e.data);
      console.log(data1Json);
    },
    //连接建立失败重连
    websocketonerror(e) {
      console.log(`连接失败的信息:`, e);
      this.initWebSocket(); // 连接失败后尝试重新连接
    },
    //关闭连接
    websocketclose(e) {
      console.log("断开连接", e);
    },

3,在 destroyed 中:

  destroyed() {
    if (this.websock) {   //页面销毁时关闭websocket
      this.websock.close();
    }
  },

相关文章

网友评论

      本文标题:vue中长链接(weosocket)使用方法

      本文链接:https://www.haomeiwen.com/subject/qwyueltx.html