在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>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值