基于vueuse分装WebSocket

基于vueuse分装WebSocket

import { useWebSocket } from '@vueuse/core'

export interface IWebSocketConfig {
  wsUrl: string
  isHeartbeat?: boolean
  isAutoReconnect?: boolean
  immediate?: boolean
  autoReconnect?: {
    retries?: number
    delay?: number
  }
  heartbeat?: {
    message?: string
    interval?: number
    pongTimeout?: number
  }
  onFailedCall?: Function
  onConnectedCall?: Function
  onDisconnectedCall?: Function
  onErrorCall?: Function
  onMessageCall?: Function
}

export const useWebSocketHook = (options?: IWebSocketConfig): any => {
  const {
    autoReconnect = {},
    isHeartbeat = false,
    isAutoReconnect = false,
    immediate = false,
    heartbeat = {},
    onConnectedCall,
    onDisconnectedCall,
    onErrorCall,
    onMessageCall,
    onFailedCall,
    wsUrl,
  } = options ?? {}

  const { status, data, send, open, close, ws } = useWebSocket(wsUrl, {
    autoReconnect: isAutoReconnect
      ? {
          retries: 3, // 最大重试次数。
          delay: 1000, // 延迟
          onFailed() {
            console.log('*** Failed to connect WebSocket after 3 retries ***')
            onFailedCall && onFailedCall()
          },
          ...autoReconnect,
        }
      : false,
    immediate: immediate,
    heartbeat: isHeartbeat
      ? {
          message: 'ping',
          interval: 1000,
          pongTimeout: 50000,
          ...heartbeat,
        }
      : false,
    onConnected(ws: WebSocket) {
      onConnectedCall && onConnectedCall(ws)
    },
    onDisconnected(ws: WebSocket, event: CloseEvent) {
      onDisconnectedCall && onDisconnectedCall(ws, event)
    },
    onError(ws: WebSocket, event: Event) {
      onErrorCall && onErrorCall(ws, event)
    },
    onMessage(ws: WebSocket, event: MessageEvent) {
      onMessageCall && onMessageCall(ws, event)
    },
  })

  return {
    status,
    data,
    send,
    open,
    close,
    ws,
  }
}

你可能感兴趣的:(前端小屋,websocket,网络协议,网络)