SocketIoClient.js 3.53 KB
/*
 * socket.io 客户端封装(与 ws/Ws.js 同协议,供 Demo / 业务推流使用)
 * 注意:项目服务端是 socket.io,不能用 uni.connectSocket 直连
 */
import io from '@/uni_modules/hyoga-uni-socket_io/uni-socket.io.js'
import config from '@/config.js'
import { WsTyps } from '@/utils/common'
import { serializeIfObject } from '@/utils/utils.js'
import { loginDevice } from './wsAuth.js'

class SocketIoClient {
  constructor(options = {}) {
    this._tag = options.logTag || 'SocketIo'
    this._ws = null
    this._deviceId = null
    this._token = null
    this._onMessage = null
    this._connected = false
  }

  get isConnected() {
    return this._connected && this._ws != null
  }

  get deviceId() {
    return this._deviceId
  }

  onMessage(handler) {
    this._onMessage = typeof handler === 'function' ? handler : null
  }

  /**
   * 登录并连接 socket.io(与 Ws.js 相同 path / auth)
   */
  async connect() {
    if (this.isConnected) {
      return true
    }

    const { code, data } = await loginDevice()
    if (code != 200) {
      throw new Error(`WS 登录失败 code=${code}`)
    }

    this._deviceId = data.id
    this._token = data.token
    this._log('info', `登录成功 deviceId=${this._deviceId}`)

    return new Promise((resolve, reject) => {
      const socket = io(config.SOCKET_SERVER, {
        path: '/websocket/',
        auth: { token: this._token, deviceId: this._deviceId },
        transports: ['websocket'],
        timeout: 5000
      })

      const timer = setTimeout(() => {
        cleanup()
        reject(new Error('socket.io 连接超时'))
      }, 8000)

      const onConnect = () => {
        cleanup()
        this._ws = socket
        this._connected = true
        this._log('info', 'socket.io 已连接')
        this._bindMessage()
        resolve(true)
      }

      const onError = (err) => {
        cleanup()
        this._log('error', `socket.io 错误 ${serializeIfObject(err)}`)
        reject(err || new Error('socket.io error'))
      }

      const onDisconnect = () => {
        this._connected = false
        this._log('warn', 'socket.io 已断开')
      }

      const cleanup = () => {
        clearTimeout(timer)
        socket.off(WsTyps.Connected, onConnect)
        socket.off(WsTyps.Eroor, onError)
      }

      socket.on(WsTyps.Connected, onConnect)
      socket.on(WsTyps.Eroor, onError)
      socket.on(WsTyps.Disconnected, onDisconnect)

      this._log('info', `连接 socket.io -> ${config.SOCKET_SERVER}/websocket/`)
    })
  }

  _bindMessage() {
    if (!this._ws || !this._onMessage) return
    this._ws.on(WsTyps.MessageTypes.Private, (data) => {
      this._onMessage(data)
    })
  }

  /**
   * 发送消息(默认 private 频道,自动带 device_id)
   * @param {object} data
   */
  send(data, type = WsTyps.MessageTypes.Private) {
    if (!this.isConnected) {
      return Promise.reject(new Error('socket.io 未连接'))
    }
    const payload = { device_id: this._deviceId, ...data }
    this._log('debug', `发送 => ${serializeIfObject(data).slice(0, 200)}`)
    this._ws.emit(type, payload)
    return Promise.resolve({ errMsg: 'emit:ok' })
  }

  disconnect() {
    this._connected = false
    if (this._ws) {
      try {
        this._ws.disconnect()
      } catch (_) {
        /* ignore */
      }
      this._ws = null
    }
    this._onMessage = null
    this._log('info', 'socket.io 已关闭')
  }

  _log(level, msg) {
    const text = `[${this._tag}] ${msg}`
    uni.$logger?.local?.[level]?.(text) || console.log(text)
  }
}

export default SocketIoClient