zhou zhou
18 小时以前 fec285d150b377d004e47f0973d298b92fe4c711
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
const DEFAULT_LOGIN_WEBSOCKET = import.meta.env.VITE_LOGIN_WEBSOCKET || 'ws://localhost:8080/ws'
 
class WebSocketClient {
  constructor(options) {
    this.ws = null
    this.url = options.url || DEFAULT_LOGIN_WEBSOCKET
    this.messageHandler = options.messageHandler || (() => {})
    this.reconnectInterval = options.reconnectInterval ?? 20 * 1e3
    this.heartbeatInterval = options.heartbeatInterval ?? 5 * 1e3
    this.pingInterval = options.pingInterval ?? 10 * 1e3
    this.reconnectTimeout = options.reconnectTimeout ?? 30 * 1e3
    this.maxReconnectAttempts = options.maxReconnectAttempts ?? 10
    this.connectionTimeout = options.connectionTimeout ?? 10 * 1e3
    this.reconnectAttempts = 0
    this.messageQueue = []
    this.detectionTimer = null
    this.timeoutTimer = null
    this.reconnectTimer = null
    this.pingTimer = null
    this.connectionTimer = null
    this.isConnected = false
    this.isConnecting = false
    this.stopReconnect = false
    this.isReconnecting = false
  }
  // 单例模式获取实例
  static getInstance(options) {
    if (!WebSocketClient.instance) {
      WebSocketClient.instance = new WebSocketClient(options)
    } else {
      WebSocketClient.instance.messageHandler = options.messageHandler || (() => {})
      if (options.url && WebSocketClient.instance.url !== options.url) {
        WebSocketClient.instance.url = options.url
        WebSocketClient.instance.reconnectAttempts = 0
        WebSocketClient.instance.init()
      }
    }
    return WebSocketClient.instance
  }
  // 初始化连接
  init() {
    this.connect(true)
  }
  connect(resetReconnectAttempts = false) {
    if (this.isConnecting) {
      console.log('正在建立WebSocket连接中...')
      return
    }
    if (this.ws?.readyState === WebSocket.OPEN) {
      console.warn('WebSocket连接已存在')
      this.flushMessageQueue()
      return
    }
    try {
      this.isConnecting = true
      this.stopReconnect = false
      if (resetReconnectAttempts) {
        this.reconnectAttempts = 0
        this.isReconnecting = false
        this.clearTimer('reconnectTimer')
      }
      this.ws = new WebSocket(this.url)
      this.clearTimer('connectionTimer')
      this.connectionTimer = setTimeout(() => {
        console.error(`WebSocket连接超时 (${this.connectionTimeout}ms):${this.url}`)
        this.handleConnectionTimeout()
      }, this.connectionTimeout)
      this.ws.onopen = (event) => this.handleOpen(event)
      this.ws.onmessage = (event) => this.handleMessage(event)
      this.ws.onclose = (event) => this.handleClose(event)
      this.ws.onerror = (event) => this.handleError(event)
    } catch (error) {
      console.error('WebSocket初始化失败:', error)
      this.isConnecting = false
      this.reconnect()
    }
  }
  // 处理连接超时
  handleConnectionTimeout() {
    if (this.ws?.readyState !== WebSocket.OPEN) {
      console.error('WebSocket连接超时,强制关闭连接')
      this.ws?.close(1e3, 'Connection timeout')
      this.isConnecting = false
      this.reconnect()
    }
  }
  // 关闭连接
  close(force) {
    this.clearAllTimers()
    this.stopReconnect = true
    this.isReconnecting = false
    this.isConnecting = false
    if (this.ws) {
      this.ws.close(force ? 1001 : 1e3, force ? 'Force closed' : 'Normal close')
      this.ws = null
    }
    this.isConnected = false
  }
  // 发送消息 - 增加消息队列
  send(data, immediate = false) {
    if (immediate && (!this.ws || this.ws.readyState !== WebSocket.OPEN)) {
      console.error('WebSocket未连接,无法立即发送消息')
      return
    }
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      console.log('WebSocket未连接,消息已加入队列等待发送')
      this.messageQueue.push(data)
      if (!this.isConnecting && !this.stopReconnect) {
        this.init()
      }
      return
    }
    try {
      this.ws.send(data)
    } catch (error) {
      console.error('WebSocket发送消息失败:', error)
      this.messageQueue.push(data)
      this.reconnect()
    }
  }
  // 发送队列中的消息
  flushMessageQueue() {
    if (this.messageQueue.length > 0 && this.ws?.readyState === WebSocket.OPEN) {
      console.log(`发送队列中的${this.messageQueue.length}条消息`)
      while (this.messageQueue.length > 0) {
        const data = this.messageQueue.shift()
        if (data) {
          try {
            this.ws?.send(data)
          } catch (error) {
            console.error('发送队列消息失败:', error)
            if (data) this.messageQueue.unshift(data)
            break
          }
        }
      }
    }
  }
  // 处理连接打开
  handleOpen(event) {
    console.log('WebSocket连接成功', event)
    this.clearTimer('connectionTimer')
    this.isConnected = true
    this.isConnecting = false
    this.isReconnecting = false
    this.stopReconnect = false
    this.reconnectAttempts = 0
    this.startHeartbeat()
    this.startPing()
    this.flushMessageQueue()
  }
  // 处理收到的消息
  handleMessage(event) {
    console.log('收到WebSocket消息:', event)
    this.resetHeartbeat()
    this.messageHandler(event)
  }
  // 处理连接关闭
  handleClose(event) {
    console.log(
      `WebSocket断开: 代码=${event.code}, 原因=${event.reason}, 干净关闭=${event.wasClean}`
    )
    const isNormalClose = event.code === 1e3
    this.isConnected = false
    this.isConnecting = false
    this.clearConnectionTimers()
    this.ws = null
    if (!this.stopReconnect && !isNormalClose) {
      this.reconnect()
    }
  }
  // 处理错误 - 增加详细错误信息
  handleError(event) {
    console.error('WebSocket连接错误:')
    console.error('错误事件:', event)
    console.error(
      '当前连接状态:',
      this.ws?.readyState ? this.getReadyStateText(this.ws.readyState) : '未初始化'
    )
    this.isConnected = false
    this.isConnecting = false
    if (!this.stopReconnect) {
      this.reconnect()
    }
  }
  closeCurrentSocketForReconnect() {
    this.clearConnectionTimers()
    this.isConnected = false
    this.isConnecting = false
    if (this.ws) {
      this.ws.onopen = null
      this.ws.onmessage = null
      this.ws.onclose = null
      this.ws.onerror = null
      if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
        this.ws.close(1001, 'Reconnect')
      }
      this.ws = null
    }
  }
  // 转换连接状态为文本描述
  getReadyStateText(state) {
    switch (state) {
      case WebSocket.CONNECTING:
        return 'CONNECTING (0) - 正在连接'
      case WebSocket.OPEN:
        return 'OPEN (1) - 已连接'
      case WebSocket.CLOSING:
        return 'CLOSING (2) - 正在关闭'
      case WebSocket.CLOSED:
        return 'CLOSED (3) - 已关闭'
      default:
        return `未知状态 (${state})`
    }
  }
  // 开始心跳检测
  startHeartbeat() {
    this.clearTimer('detectionTimer')
    this.clearTimer('timeoutTimer')
    this.detectionTimer = setTimeout(() => {
      this.isConnected = this.ws?.readyState === WebSocket.OPEN
      if (!this.isConnected) {
        console.warn('WebSocket心跳检测失败,尝试重连')
        this.reconnect()
        this.timeoutTimer = setTimeout(() => {
          console.warn('WebSocket重连超时')
          this.close()
        }, this.reconnectTimeout)
      }
    }, this.heartbeatInterval)
  }
  // 重置心跳检测
  resetHeartbeat() {
    this.clearTimer('detectionTimer')
    this.clearTimer('timeoutTimer')
    this.startHeartbeat()
  }
  // 开始发送ping消息
  startPing() {
    this.clearTimer('pingTimer')
    this.pingTimer = setInterval(() => {
      if (this.ws?.readyState !== WebSocket.OPEN) {
        console.warn('WebSocket未连接,停止发送ping')
        this.clearTimer('pingTimer')
        this.reconnect()
        return
      }
      try {
        this.ws.send('ping')
        console.log('发送ping消息')
      } catch (error) {
        console.error('发送ping消息失败:', error)
        this.clearTimer('pingTimer')
        this.reconnect()
      }
    }, this.pingInterval)
  }
  // 重连 - 增加重连次数限制
  reconnect() {
    if (this.stopReconnect || this.isConnecting || this.reconnectInterval <= 0) {
      return
    }
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error(`已达到最大重连次数(${this.maxReconnectAttempts}),停止重连`)
      this.close(true)
      return
    }
    this.reconnectAttempts++
    this.isReconnecting = true
    this.closeCurrentSocketForReconnect()
    const delay = this.calculateReconnectDelay()
    console.log(
      `将在${delay / 1e3}秒后尝试重新连接(第${this.reconnectAttempts}/${this.maxReconnectAttempts}次)`
    )
    this.clearTimer('reconnectTimer')
    this.reconnectTimer = setTimeout(() => {
      console.log(`尝试重新连接WebSocket(第${this.reconnectAttempts}次)`)
      this.connect(false)
    }, delay)
  }
  // 计算重连延迟 - 指数退避策略
  calculateReconnectDelay() {
    const jitter = Math.random() * 1e3
    const baseDelay = Math.min(
      this.reconnectInterval * Math.pow(1.5, this.reconnectAttempts - 1),
      this.reconnectInterval * 5
    )
    return baseDelay + jitter
  }
  // 清除指定定时器
  clearTimer(timerName) {
    if (this[timerName]) {
      clearTimeout(this[timerName])
      this[timerName] = null
    }
  }
  // 清除所有定时器
  clearAllTimers() {
    this.clearConnectionTimers()
    this.clearTimer('reconnectTimer')
  }
  clearConnectionTimers() {
    this.clearTimer('detectionTimer')
    this.clearTimer('timeoutTimer')
    this.clearTimer('pingTimer')
    this.clearTimer('connectionTimer')
  }
  // 获取当前连接状态
  get isWebSocketConnected() {
    return this.isConnected
  }
  // 获取当前连接状态文本
  get connectionStatusText() {
    if (this.isConnecting) return '正在连接'
    if (this.isConnected) return '已连接'
    if (this.isReconnecting && this.reconnectAttempts > 0)
      return `重连中(${this.reconnectAttempts}/${this.maxReconnectAttempts})`
    return '已断开'
  }
  // 销毁实例
  static destroyInstance() {
    if (WebSocketClient.instance) {
      WebSocketClient.instance.close()
      WebSocketClient.instance = null
    }
  }
}
 
WebSocketClient.instance = null
 
export default WebSocketClient