Vue 之 Websocket

话不多说,直接上代码吧

<script>
export default {
  name: "indexPage",
  props: {},
  components: {},
  data() {
    return {
      websock: null, //websocket对象
      maxReconnect: 5, //最大重连次数
      wsUrl: "ws://192.168.1.1",
    };
  },
  methods: {
    /**
     * 监听方法
     */
    // 初始化webSocket
    initWebSocket() {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持WebSocket");
        return false;
      }
      console.log("初始化连接websocket");
      this.websock = new WebSocket(this.wsUrl);
      //连接成功
      this.websock.onopen = this.websocketonopen;
      //接收后端返回的数据
      this.websock.onmessage = this.websocketonmessage;
      //连接错误触发
      this.websock.onerror = this.websocketonerror;
      //断开连接触发
      this.websock.onclose = this.websocketclose;
    },
    //连接成功
    websocketonopen() {
      console.log("WebSocket连接成功");
      // 判断是否在正常连接状态
      if (this.websock.readyState === 1) {
        // 发送消息
        this.websockSend("1001");
      }
    },
    //接收后端返回的数据
    websocketonmessage(e) {
      let dataJson = JSON.parse(e.data);
    },
    //连接错误触发
    websocketonerror(e) {
      console.log(`连接发生错误的信息:`, e);
      // this.reconnect();

      // 其实可以不在这重连,因为发生错误后会自动断开连接,可能会导致触发两次重连
    },
    //断开连接触发
    websocketclose(e) {
      console.log("断开连接", e);
      this.reconnect();
    },
    // 尝试重连
    reconnect() {
      console.log("尝试重连");
      setTimeout(() => {
        // this.maxReconnect-- // 不做限制 连不上一直重连
        this.initWebSocket();
      }, 60 * 1000);
    },

    /**
     * 请求数据
     */
    //websock请求
    websockSend(command) {
      // 把后台需要的参数数据传过去
      let params = {};
      params.data = {
        command,
      };
      //发给后端的数据需要字符串化
      this.websock.send(JSON.stringify(params));
    },
  },
  mounted() {
    this.initWebSocket();
  },
  computed: {},
  watch: {},
  filters: {},
  beforeDestroy() {
    //页面销毁时关闭ws连接
    if (this.websock) {
      this.websock.close(); // 关闭websocket
    }
  },
};
</script>

猜你喜欢

转载自blog.csdn.net/a15297701931/article/details/119111803