• WebSocket封装(TypeScript、单例模式、自动重连、事件监听、Vue中使用)


    export type AutoReconnectOptions = boolean | {
      maxRetries?: number
      retryInterval?: number
      onMaxRetriesReached?: Function
    }
    
    export enum ConnectionStatus {
      Disconnected = 'DISCONNECTED',
      Connected = 'CONNECTED',
      Error = 'ERROR'
    }
    
    class SocketService {
      private static instance: SocketService
      private ws: WebSocket | null = null
      private listeners: Record<string, Function[]> = {}
      private autoReconnect: AutoReconnectOptions = true
      private retries: number = 0
      private connectionStatus: ConnectionStatus = ConnectionStatus.Disconnected
    
      private constructor() {
        this.connect()
      }
    
      public static getInstance(): SocketService {
        if (!SocketService.instance) {
          SocketService.instance = new SocketService()
        }
        return SocketService.instance
      }
    
      public setAutoReconnectOptions(options: AutoReconnectOptions) {
        this.autoReconnect = options
      }
    
      public connect() {
        this.ws = new WebSocket('ws://localhost:3000/ws')
        this.ws.onopen = () => {
          this.connectionStatus = ConnectionStatus.Connected
          this.emit('connected', null)
        }
        this.ws.onerror = () => {
          this.connectionStatus = ConnectionStatus.Error
          this.emit('error', null)
        }
        this.ws.onclose = () => {
          this.connectionStatus = ConnectionStatus.Disconnected
          this.emit('disconnected', null)
          if (this.shouldReconnect()) {
            setTimeout(() => this.connect(), this.getRetryInterval())
          }
        }
        this.ws.onmessage = (event) => {
          this.emit('message', event.data)
        }
      }
    
      private shouldReconnect(): boolean {
        if (typeof this.autoReconnect === 'boolean') {
          return this.autoReconnect
        } else if (this.autoReconnect) {
          const { maxRetries } = this.autoReconnect
    
          if (maxRetries !== undefined) {
            if (this.retries < maxRetries) {
              this.retries++
              return true
            } else if (this.retries >= maxRetries) {
              this.autoReconnect.onMaxRetriesReached && this.autoReconnect.onMaxRetriesReached()
              return false
            }
          }
        }
        return false
      }
    
      private getRetryInterval(): number {
        if (typeof this.autoReconnect === 'boolean') {
          return 1000
        } else if (this.autoReconnect && this.autoReconnect.retryInterval) {
          return this.autoReconnect.retryInterval
        }
        return 1000
      }
    
      public send(data: any) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
          this.ws.send(JSON.stringify(data))
        } else {
          console.error('WebSocket 连接未打开')
        }
      }
    
      public close() {
        if (this.ws) {
          this.ws.close()
        }
      }
    
      private emit(event: string, data: any) {
        if (!this.listeners[event]) {
          return
        }
        this.listeners[event].forEach((listener) => listener(data))
      }
    
      public on(event: string, listener: Function) {
        if (!this.listeners[event]) {
          this.listeners[event] = []
        }
        this.listeners[event].push(listener)
        if (event === 'connected' && this.connectionStatus === ConnectionStatus.Connected) {
          listener()
        }
      }
    
      public off(event: string, listener: Function) {
        if (!this.listeners[event]) {
          return
        }
        this.listeners[event] = this.listeners[event].filter((l) => l !== listener)
      }
    
      public getConnectionStatus(): ConnectionStatus {
        return this.connectionStatus
      }
    
      public watchConnectionStatus(callback: (status: ConnectionStatus) => void) {
        this.on('connected', () => callback(ConnectionStatus.Connected))
        this.on('disconnected', () => callback(ConnectionStatus.Disconnected))
        this.on('error', () => callback(ConnectionStatus.Error))
      }
    }
    
    export default SocketService
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135

    在 Vue3 中使用:

    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    可以在不同的 Vue 组件/页面中通过 SocketService.getInstance() 获取同一个 WebSocket 连接,监听数据接收以及发送消息。

  • 相关阅读:
    Jetpack:014-Jetpack中的小红点
    代谢组学分析平台(二)
    unity脚本_Vector3 c#
    vue请求后端数据和跨域问题
    (续)SSM整合之springmvc笔记(RESTful之HiddenHttpMethodFilter源码解析)(P147)了解
    一文详解GaussDB(DWS) 的并发管控和内存管控
    BDD - SpecFlow Context Injection 上下文依赖注入
    【Java和C++】什么是多态
    MySQL总结 (思维导图,常用)
    python安装.whl文件
  • 原文地址:https://blog.csdn.net/qq_44600038/article/details/138153216