在vue项目中封装并使用WebSocket(2)

创建一个websocket组件

<script>
export default {
  name: "index",
  props: {
    wsUrl: {
      type: String,
      require: true,
    },
  },
  data() {
    return {
      socket: "",
    };
  },
  watch: {
    wsUrl: {
      immediate: true,
      handler() {
        this.init();
      },
    },
  },
  methods: {
    init() {
      console.log(this.wsUrl, this.socket);
      console.log("socket-begin");
      if (this.wsUrl && this.wsUrl.trim() !== "") {
        if (typeof WebSocket === "undefined") {
          console.error("您的浏览器不支持socket");
          this.$message({
            message: "您的浏览器不支持socket",
            type: "warning",
          });
        } else {
          if (this.socket) {
            this.socket.close();
          }
          // 实例化socket
          this.socket = new WebSocket(this.wsUrl);
          // 监听socket连接
          this.socket.onopen = this.open;
          // 监听socket错误信息
          this.socket.onerror = this.error;
          // 监听socket消息
          this.socket.onmessage = this.getMessage;
          // 销毁监听
          this.socket.onclose = this.close;
        }
      }
    },
    open() {
      console.log("socket连接成功");
      this.$emit("open");
    },
    error() {
      console.log("连接错误");
      this.$emit("error");
    },
    getMessage(msg) {
      console.log(msg, msg.data);
      this.$emit("getMessage", msg);
    },
    send(msg) {
      if (this.socket) {
        this.socket.send(msg);
      } else {
        console.error("socket is not exists");
      }
    },
    close() {
      if (this.socket) {
        this.socket.close();
        console.log("socket已经关闭");
        this.$emit("close");
      } else {
        console.error("socket is not exists");
      }
    },
  },
  beforeDestroy() {
    this.close();
  },
};
</script>

在需要的组件中引用注册使用


 <template>
    <div class="view">  
      <!-- websocket连接 -->
      <WebSocket :wsUrl="wsUrl" ref="WS" @open="open" @error="error" @getMessage="getMessage" @close="close" />
    </div>
  </template>
    
  <script>
  import WebSocket from "@/components/websocket";
  export default {
    components: {
      WebSocket,
    },
    data() {
      return {
        wsUrl: "", // webSocket 链接路径
      };
    },
    methods: {
      reCallCopy(params) {
            this.wsUrl = `ws://192.168.43.248:43504/backNotifySocket`; 
      },
      // 获取信息事件
      getMessage(msg) {
        // 判断返回的数据是否是 json
        if (msg.data === "WEBSOCKET_SESSION_CLOSE") {
          this.$message({
            message: `${this.tipsText}失败!`,
            showClose: true,
            type: "warning",
          });
        } else {
          let resObj = JSON.parse(msg.data);
        }
        this.$refs.WS.close(); // 关闭链接
      },
      // 连接成功事件
      open() {
        console.log("socket连接成功!");
      },
      // 连接失败事件
      error() {
        console.log("-component-连接错误!");
        this.$message({
          message: `${this.tipsText}失败!`,
          type: "warning",
          showClose: true,
        });
        this.$refs.WS.close(); // 关闭链接
        this.wsUrl = "";
        this.$store.commit("publicModule/setViewLoading", false);
      },
      // 关闭 websocket
      close() {
        console.log("socket已经关闭,召测结束");
        this.$store.commit("publicModule/setViewLoading", false);
      },
      // #endregion
    },
  };
  </script>

上一篇:Android 静默安装成功后自启动


下一篇:node.js中常用的命令及示例