SocketClient.js 12.9 KB
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 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
/*
 * @Description: 基于 uni.connectSocket / SocketTask 的 WebSocket 封装(纯传输层,不含业务)
 * 每个实例每类事件仅保留一个 handler,重复注册会覆盖
 */
import { serializeIfObject } from '@/utils/utils.js'
import { SocketState, DEFAULT_OPTIONS } from './constants.js'
import { createSocketTask, isSocketTask } from './connectSocketTask.js'

function isArrayBuffer(val) {
  return typeof ArrayBuffer !== 'undefined' && val instanceof ArrayBuffer
}

class SocketClient {
  /**
   * @param {object} [defaultOptions] 实例级默认配置,connect 时可覆盖
   */
  constructor(defaultOptions = {}) {
    this._options = { ...DEFAULT_OPTIONS, ...defaultOptions }
    this._socketTask = null
    this._state = SocketState.IDLE
    this._onOpen = null
    this._onMessage = null
    this._onError = null
    this._onClose = null
    this._onStateChange = null
    this._onReconnecting = null
    this._connectOptions = null
    this._manualClose = false
    this._reconnectTimer = null
    this._reconnectAttempts = 0
    this._sendQueue = []
    this._boundHandlers = null
  }

  get state() {
    return this._state
  }

  get socketTask() {
    return this._socketTask
  }

  get isConnected() {
    return this._state === SocketState.OPEN && this._socketTask != null
  }

  get tag() {
    return this._options.logTag || 'SocketClient'
  }

  /**
   * 建立连接
   * @param {object} options
   * @param {string} options.url 必填,ws / wss 地址
   * @param {Function} [options.onOpen]
   * @param {Function} [options.onMessage]
   * @param {Function} [options.onError]
   * @param {Function} [options.onClose]
   * @param {Function} [options.onStateChange]
   * @param {Function} [options.onReconnecting]
   */
  connect(options = {}) {
    const { onOpen, onMessage, onError, onClose, onStateChange, onReconnecting, ...rest } = options
    if (onOpen) this.onOpen(onOpen)
    if (onMessage) this.onMessage(onMessage)
    if (onError) this.onError(onError)
    if (onClose) this.onClose(onClose)
    if (onStateChange) this.onStateChange(onStateChange)
    if (onReconnecting) this.onReconnecting(onReconnecting)

    const merged = { ...this._options, ...rest }
    if (!merged.url) {
      const err = new Error('connect 缺少 url')
      this._log('error', `connect 失败: ${err.message}`)
      options.fail?.(err)
      options.complete?.(err)
      return
    }

    if (this._state === SocketState.CONNECTING || this._state === SocketState.OPEN) {
      this._log('warn', `connect 忽略: 当前状态 ${this._state}`)
      options.success?.({ errMsg: 'already connected or connecting' })
      options.complete?.({ errMsg: 'already connected or connecting' })
      return
    }

    this._options = merged
    this._connectOptions = { ...merged, onOpen, onMessage, onError, onClose, onStateChange, onReconnecting }
    this._manualClose = false
    this._clearReconnectTimer()
    this._setState(SocketState.CONNECTING)
    this._log('info', `connecting -> ${merged.url}`)

    this._openSocket(merged, options)
  }

  _openSocket(merged, options) {
    try {
      const task = createSocketTask({
        url: merged.url,
        header: merged.header || {},
        protocols: merged.protocols || [],
        fail: (err) => {
          this._log('error', `connectSocket fail: ${serializeIfObject(err)}`)
          this._setState(SocketState.CLOSED)
          options.fail?.(err)
          options.complete?.(err)
          this._scheduleReconnect()
        }
      })
      this._socketTask = task
      this._bindSocketTask(task)
      options.success?.({ errMsg: 'connectSocket:ok' })
      options.complete?.({ errMsg: 'connectSocket:ok' })
    } catch (e) {
      this._log('error', `connect 异常: ${e.message}`)
      this._setState(SocketState.CLOSED)
      options.fail?.(e)
      options.complete?.(e)
      this._scheduleReconnect()
    }
  }

  close(options = {}) {
    this._manualClose = true
    this._clearReconnectTimer()
    this._sendQueue = []
    this._reconnectAttempts = 0

    if (!this._socketTask) {
      this._setState(SocketState.CLOSED)
      return Promise.resolve({ errMsg: 'close:ok' })
    }

    this._setState(SocketState.CLOSING)
    this._log('info', 'closing...')

    return new Promise((resolve) => {
      this._socketTask.close({
        code: options.code,
        reason: options.reason || '',
        success: (res) => {
          this._log('info', `close success: ${serializeIfObject(res)}`)
          resolve(res)
        },
        fail: (err) => {
          this._log('warn', `close fail: ${serializeIfObject(err)}`)
          resolve(err)
        },
        complete: () => {
          this._cleanupSocketTask()
          this._setState(SocketState.CLOSED)
        }
      })
    })
  }

  send(data, options = {}) {
    const payload = this._normalizeSendData(data)

    if (!this.isConnected) {
      if (this._options.enableSendQueue) {
        return this._enqueueSend(payload, options)
      }
      const err = { errMsg: 'send:fail socket not connected' }
      this._log('warn', err.errMsg)
      options.fail?.(err)
      options.complete?.(err)
      return Promise.reject(err)
    }

    return this._doSend(payload, options)
  }

  /** @param {Function|null} handler 传 null 可清除 */
  onMessage(handler) {
    this._onMessage = typeof handler === 'function' ? handler : null
    return this
  }

  onOpen(handler) {
    this._onOpen = typeof handler === 'function' ? handler : null
    return this
  }

  onError(handler) {
    this._onError = typeof handler === 'function' ? handler : null
    return this
  }

  onClose(handler) {
    this._onClose = typeof handler === 'function' ? handler : null
    return this
  }

  onStateChange(handler) {
    this._onStateChange = typeof handler === 'function' ? handler : null
    return this
  }

  onReconnecting(handler) {
    this._onReconnecting = typeof handler === 'function' ? handler : null
    return this
  }

  clearHandlers() {
    this._onOpen = null
    this._onMessage = null
    this._onError = null
    this._onClose = null
    this._onStateChange = null
    this._onReconnecting = null
  }

  destroy() {
    this._manualClose = true
    this._clearReconnectTimer()
    this._sendQueue = []
    this.clearHandlers()
    if (this._socketTask) {
      try {
        this._socketTask.close({})
      } catch (_) {
        /* ignore */
      }
    }
    this._cleanupSocketTask()
    this._setState(SocketState.CLOSED)
    this._log('info', 'destroyed')
  }

  _bindSocketTask(task) {
    if (!isSocketTask(task)) {
      this._log('error', 'connectSocket 未返回 SocketTask')
      this._setState(SocketState.CLOSED)
      this._scheduleReconnect()
      return
    }
    this._unbindSocketTask()
    const handlers = {
      onOpen: (res) => {
        this._reconnectAttempts = 0
        this._setState(SocketState.OPEN)
        this._log('info', `opened: ${serializeIfObject(res)}`)
        this._invoke(this._onOpen, res)
        this._flushSendQueue()
      },
      onMessage: (res) => {
        const parsed = this._parseMessage(res)
        this._log('debug', `message <= ${this._previewMessage(parsed)}`)
        this._invoke(this._onMessage, parsed)
      },
      onError: (err) => {
        this._log('error', `error: ${serializeIfObject(err)}`)
        this._invoke(this._onError, err)
      },
      onClose: (res) => {
        this._log('warn', `closed: ${serializeIfObject(res)}`)
        this._invoke(this._onClose, res)
        this._cleanupSocketTask()
        this._setState(SocketState.CLOSED)
        if (!this._manualClose) {
          this._scheduleReconnect()
        }
      }
    }
    this._boundHandlers = handlers
    task.onOpen(handlers.onOpen)
    task.onMessage(handlers.onMessage)
    task.onError(handlers.onError)
    task.onClose(handlers.onClose)
  }

  _unbindSocketTask() {
    if (!this._socketTask || !this._boundHandlers) return
    try {
      this._socketTask.offOpen?.(this._boundHandlers.onOpen)
      this._socketTask.offMessage?.(this._boundHandlers.onMessage)
      this._socketTask.offError?.(this._boundHandlers.onError)
      this._socketTask.offClose?.(this._boundHandlers.onClose)
    } catch (_) {
      /* 部分平台无 off* API */
    }
    this._boundHandlers = null
  }

  _cleanupSocketTask() {
    this._unbindSocketTask()
    this._socketTask = null
  }

  _normalizeSendData(data) {
    if (typeof data === 'string' || isArrayBuffer(data)) {
      return data
    }
    return JSON.stringify(data)
  }

  _doSend(data, options = {}) {
    this._log('debug', `message => ${this._previewMessage(data)}`)
    const sendOpts = {
      data,
      success: (res) => {
        options.success?.(res)
        options.complete?.(res)
        resolveRef(res)
      },
      fail: (err) => {
        this._log('warn', `send fail: ${serializeIfObject(err)}`)
        options.fail?.(err)
        options.complete?.(err)
        rejectRef(err)
      }
    }
    let resolveRef
    let rejectRef
    return new Promise((resolve, reject) => {
      resolveRef = resolve
      rejectRef = reject
      this._socketTask.send(sendOpts)
    })
  }

  _enqueueSend(data, options) {
    if (this._sendQueue.length >= this._options.sendQueueMax) {
      const dropped = this._sendQueue.shift()
      this._log('warn', `send 队列已满,丢弃最旧一条: ${this._previewMessage(dropped?.data)}`)
    }
    return new Promise((resolve, reject) => {
      this._sendQueue.push({ data, options, resolve, reject })
      this._log('debug', `send 入队,队列长度 ${this._sendQueue.length}`)
    })
  }

  _flushSendQueue() {
    if (!this._sendQueue.length || !this.isConnected) return
    const queue = this._sendQueue.splice(0)
    this._log('info', `flush send 队列 ${queue.length} 条`)
    queue.forEach((item) => {
      this._doSend(item.data, item.options).then(item.resolve).catch(item.reject)
    })
  }

  _parseMessage(res) {
    const raw = res?.data
    if (!this._options.autoParseJson || typeof raw !== 'string') {
      return { raw, parsed: null, meta: res }
    }
    const text = raw.trim()
    if (!text || (text[0] !== '{' && text[0] !== '[')) {
      return { raw, parsed: null, meta: res }
    }
    try {
      return { raw, parsed: JSON.parse(text), meta: res }
    } catch (_) {
      return { raw, parsed: null, meta: res }
    }
  }

  _scheduleReconnect() {
    if (this._manualClose || !this._options.reconnect || !this._connectOptions?.url) {
      return
    }
    const max = this._options.reconnectMaxRetries
    if (max >= 0 && this._reconnectAttempts >= max) {
      this._log('error', `重连已达上限 ${max},停止重连`)
      return
    }

    this._clearReconnectTimer()
    this._reconnectAttempts += 1
    const delay = this._options.reconnectInterval
    this._log('warn', `将在 ${delay}ms 后进行第 ${this._reconnectAttempts} 次重连`)
    this._invoke(this._onReconnecting, {
      attempt: this._reconnectAttempts,
      delay
    })

    this._reconnectTimer = setTimeout(() => {
      this._reconnectTimer = null
      if (this._manualClose) return
      const {
        url,
        header,
        protocols,
        onOpen,
        onMessage,
        onError,
        onClose,
        onStateChange,
        onReconnecting,
        success,
        fail,
        complete,
        ...rest
      } = this._connectOptions
      this._setState(SocketState.IDLE)
      this.connect({
        url,
        header,
        protocols,
        onOpen,
        onMessage,
        onError,
        onClose,
        onStateChange,
        onReconnecting,
        ...rest,
        success,
        fail,
        complete
      })
    }, delay)
  }

  _clearReconnectTimer() {
    if (this._reconnectTimer != null) {
      clearTimeout(this._reconnectTimer)
      this._reconnectTimer = null
    }
  }

  _setState(next) {
    if (this._state === next) return
    const prev = this._state
    this._state = next
    this._invoke(this._onStateChange, { prev, next })
  }

  _invoke(handler, payload) {
    if (typeof handler !== 'function') return
    try {
      handler(payload)
    } catch (e) {
      this._log('error', `handler 回调异常: ${e.message}`)
    }
  }

  _previewMessage(data) {
    if (isArrayBuffer(data)) {
      return `[ArrayBuffer ${data.byteLength}]`
    }
    if (typeof data === 'string') {
      return data.length > 200 ? `${data.slice(0, 200)}...` : data
    }
    return serializeIfObject(data)
  }

  _log(level, msg) {
    const text = `[${this.tag}] ${msg}`
    const logger = uni.$logger?.local
    if (logger?.[level]) {
      logger[level](text)
      return
    }
    if (level === 'error') console.error(text)
    else if (level === 'warn') console.warn(text)
    else console.log(text)
  }
}

let _defaultInstance = null

SocketClient.getInstance = function getInstance(options) {
  if (!_defaultInstance) {
    _defaultInstance = new SocketClient(options)
  }
  return _defaultInstance
}

SocketClient.resetInstance = function resetInstance() {
  if (_defaultInstance) {
    _defaultInstance.destroy()
    _defaultInstance = null
  }
}

export default SocketClient