Lzh on GitHub

响应式 WebSocket 客户端。

用法

import { useWebSocket } from '@vueuse/core'

const { status, data, send, open, close } = useWebSocket('ws://websocketurl')

有关更多选项,请参阅 类型声明

immediate

默认启用。

当调用组合式函数时,会立即建立连接

autoConnect

默认启用。

如果 url 作为 ref 提供,当 url 更改时,它将自动重新连接到新的 url

autoClose

默认启用。

当触发 beforeunload 事件相关效果作用域停止时,这将自动调用 close()

autoReconnect (自动重新连接)

错误时自动重新连接(默认禁用)。

const { status, data, close } = useWebSocket('ws://websocketurl', {
  autoReconnect: true,
})

或者,你可以更精细地控制其行为

const { status, data, close } = useWebSocket('ws://websocketurl', {
  autoReconnect: {
    retries: 3, // 重试次数
    delay: 1000, // 延迟时间(毫秒)
    onFailed() {
      alert('连接 WebSocket 3 次重试后失败')
    },
  },
})

显式调用 close() 不会触发自动重新连接。

heartbeat (心跳)

通常的做法是每隔给定时间发送一条小消息(心跳)以保持连接活动。在此函数中,我们提供了一个方便的辅助函数来执行此操作:

const { status, data, close } = useWebSocket('ws://websocketurl', {
  heartbeat: true,
})

或者,你可以更精细地控制

const { status, data, close } = useWebSocket('ws://websocketurl', {
  heartbeat: {
    message: 'ping', // 心跳消息
    interval: 1000,  // 间隔时间(毫秒)
    pongTimeout: 1000, // pong 超时时间(毫秒)
  },
})

Sub-protocols (子协议)

要使用的一个或多个子协议列表,在此处为 soapwamp

import { useWebSocket } from '@vueuse/core'

const { status, data, send, open, close } = useWebSocket('ws://websocketurl', {
  protocols: ['soap'], // ['soap', 'wamp']
})

类型声明

export type WebSocketStatus = "OPEN" | "CONNECTING" | "CLOSED"
export type WebSocketHeartbeatMessage = string | ArrayBuffer | Blob
export interface UseWebSocketOptions {
  onConnected?: (ws: WebSocket) => void
  onDisconnected?: (ws: WebSocket, event: CloseEvent) => void
  onError?: (ws: WebSocket, event: Event) => void
  onMessage?: (ws: WebSocket, event: MessageEvent) => void
  /**
   * Send heartbeat for every x milliseconds passed
   *
   * @default false
   */
  heartbeat?:
    | boolean
    | {
        /**
         * Message for the heartbeat
         *
         * @default 'ping'
         */
        message?: MaybeRefOrGetter<WebSocketHeartbeatMessage>
        /**
         * Response message for the heartbeat, if undefined the message will be used
         */
        responseMessage?: MaybeRefOrGetter<WebSocketHeartbeatMessage>
        /**
         * Interval, in milliseconds
         *
         * @default 1000
         */
        interval?: number
        /**
         * Heartbeat response timeout, in milliseconds
         *
         * @default 1000
         */
        pongTimeout?: number
      }
  /**
   * Enabled auto reconnect
   *
   * @default false
   */
  autoReconnect?:
    | boolean
    | {
        /**
         * Maximum retry times.
         *
         * Or you can pass a predicate function (which returns true if you want to retry).
         *
         * @default -1
         */
        retries?: number | ((retried: number) => boolean)
        /**
         * Delay for reconnect, in milliseconds
         *
         * @default 1000
         */
        delay?: number
        /**
         * On maximum retry times reached.
         */
        onFailed?: Fn
      }
  /**
   * Immediately open the connection when calling this composable
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Automatically connect to the websocket when URL changes
   *
   * @default true
   */
  autoConnect?: boolean
  /**
   * Automatically close a connection
   *
   * @default true
   */
  autoClose?: boolean
  /**
   * List of one or more sub-protocol strings
   *
   * @default []
   */
  protocols?: string[]
}
export interface UseWebSocketReturn<T> {
  /**
   * Reference to the latest data received via the websocket,
   * can be watched to respond to incoming messages
   */
  data: Ref<T | null>
  /**
   * The current websocket status, can be only one of:
   * 'OPEN', 'CONNECTING', 'CLOSED'
   */
  status: ShallowRef<WebSocketStatus>
  /**
   * Closes the websocket connection gracefully.
   */
  close: WebSocket["close"]
  /**
   * Reopen the websocket connection.
   * If there the current one is active, will close it before opening a new one.
   */
  open: Fn
  /**
   * Sends data through the websocket connection.
   *
   * @param data
   * @param useBuffer when the socket is not yet open, store the data into the buffer and sent them one connected. Default to true.
   */
  send: (data: string | ArrayBuffer | Blob, useBuffer?: boolean) => boolean
  /**
   * Reference to the WebSocket instance.
   */
  ws: Ref<WebSocket | undefined>
}
/**
 * Reactive WebSocket client.
 *
 * @see https://vueuse.org/useWebSocket
 * @param url
 */
export declare function useWebSocket<Data = any>(
  url: MaybeRefOrGetter<string | URL | undefined>,
  options?: UseWebSocketOptions,
): UseWebSocketReturn<Data>