Skip to content

useWebSocket

反应式 WebSocket 客户端。

¥Reactive WebSocket client.

用法

¥Usage

js
import { useWebSocket } from '@vueuse/core'

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

请参阅 类型声明 了解更多选项。

¥See the Type Declarations for more options.

即时

¥Immediate

自动连接(默认启用)。

¥Auto-connect (enabled by default).

这会自动为你调用 open(),你不需要自己调用它。

¥This will call open() automatically for you and you don't need to call it by yourself.

如果 url 作为 ref 提供,这还控制当其值更改时是否重新建立连接(或者是否需要再次调用 open() 以使更改生效)。

¥If url is provided as a ref, this also controls whether a connection is re-established when its value is changed (or whether you need to call open() again for the change to take effect).

自动关闭

¥Auto-close

自动关闭连接(默认启用)。

¥Auto-close-connection (enabled by default).

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

¥This will call close() automatically when the beforeunload event is triggered or the associated effect scope is stopped.

自动重连

¥Auto-reconnection

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

¥Reconnect on errors automatically (disabled by default).

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

或者对其行为进行更多控制:

¥Or with more controls over its behavior:

js
const { status, data, close } = useWebSocket('ws://websocketurl', {
  autoReconnect: {
    retries: 3,
    delay: 1000,
    onFailed() {
      alert('Failed to connect WebSocket after 3 retries')
    },
  },
})

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

¥Explicitly calling close() won't trigger the auto reconnection.

心跳

¥Heartbeat

通常的做法是在每个给定时间过去后发送一条小消息(心跳)以保持连接处于活动状态。在此函数中,我们提供了一个方便的助手来完成此操作:

¥It's common practice to send a small message (heartbeat) for every given time passed to keep the connection active. In this function we provide a convenient helper to do it:

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

或者使用更多控件:

¥Or with more controls:

js
const { status, data, close } = useWebSocket('ws://websocketurl', {
  heartbeat: {
    message: 'ping',
    interval: 1000,
    pongTimeout: 1000,
  },
})

子协议

¥Sub-protocols

要使用的一个或多个子协议的列表,在本例中为肥皂和 wamp。

¥List of one or more subprotocols to use, in this case soap and wamp.

js
import { useWebSocket } from '@vueuse/core'

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

类型声明

显示类型声明
typescript
export type WebSocketStatus = "OPEN" | "CONNECTING" | "CLOSED"
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?: string | ArrayBuffer | Blob
        /**
         * Response message for the heartbeat, if undefined the message will be used
         */
        responseMessage?: string | ArrayBuffer | Blob
        /**
         * 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 | (() => boolean)
        /**
         * Delay for reconnect, in milliseconds
         *
         * @default 1000
         */
        delay?: number
        /**
         * On maximum retry times reached.
         */
        onFailed?: Fn
      }
  /**
   * Automatically open a connection
   *
   * @default true
   */
  immediate?: 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: Ref<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>

源代码

源代码文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号