组件化 websocket

发布于:2025-06-14 ⋅ 阅读:(27) ⋅ 点赞:(0)

实时数据响应,组件化websocket减少代码冗余

组件定义 websocket.vue

<template>
  <div></div>
</template>

<script>

export default {
  data() {
    return {
      webSocket: null, // webSocket实例
      lockReconnect: false, // 重连锁,避免多次重连
      maxReconnect: 3, // 最大重连次数, -1 标识无限重连
      reconnectTime: 0, // 重连尝试次数
    };
  },

  created() {
    this.initWebSocket()
  },
  destroyed: function () {
    this.webSocket.close()
  },

  //方法集合
  methods: {
    /**
       * 初始化 weoSocket
       */
    initWebSocket() {
      // ws地址 
      const host = 'XXXXXXX'
      const wsUri = `ws://${host}:3000`
      console.log(wsUri)
      // 建立连接
      this.webSocket = new WebSocket(wsUri)
      // 连接成功
      this.webSocket.onopen = this.onOpen
      // 连接错误
      this.webSocket.onerror = this.onError
      // 接收信息
      this.webSocket.onmessage = this.onMessage
      // 连接关闭
      this.webSocket.onclose = this.onClose
    },


    /**
         * 连接成功事件
         */
    onOpen() {
      console.log('WebSocket connection success')
      this.reconnectTime = 0
    },
       /**
     * 数据发送
     * @param msg
     */
    send(msg) {
      //数据发送
      this.webSocket.send(msg)
      console.log('Websocket send:',msg)
    },
    /**
     * 连接失败事件
     * @param e
     */
    onError(e) {
      //错误
      console.log(`WebSocket connection error:${e.code} ${e.reason} ${e.wasClean}`)
      //重连
      // this.reconnect()
    },
    /**
     * 连接关闭事件
     * @param e
     */
    onClose(e) {
      //关闭
      console.log(`WebSocket connection closed:${e.code} ${e.reason} ${e.wasClean}`)
      //重连
      // this.reconnect()
    },
    /**
         * 重新连接
         */
    reconnect() {
      if (this.lockReconnect || (this.maxReconnect !== -1 && this.reconnectTime > this.maxReconnect)) {
        return
      }
      this.lockReconnect = true
      setTimeout(() => {
        this.reconnectTime++
        // 建立新连接
        this.initWebSocket()
        this.lockReconnect = false
      }, 5000)
    },

       /**
     * 接收服务器推送的信息
     * @param msgEvent
     */
    onMessage(msgEvent) {
      // console.log('日志信息打印:',msgEvent)
      this.$emit('onMessage', msgEvent.data)
    },
  },

}
</script>


组件引用

        <myWebsocket v-if="dialogVisible" @onMessage="getMsg" />