Skip to content

useWebSocket

Category
Export Size
1.44 kB
Last Changed
last month

响应式的 WebSocket 客户端。

用法

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

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

查看 类型声明 获取更多选项。

immediate

默认启用。

在调用组合式函数时立即建立连接。

autoConnect

默认启用。

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

autoClose

默认启用。

这将在触发 beforeunload 事件或关联的效果作用域停止时自动调用 close()

autoReconnect

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

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

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

js
const { status, data, close } = useWebSocket('ws://websocketurl', {
  autoReconnect: {
    retries: 3,
    delay: 1000,
    onFailed() {
      alert('在 3 次重试后连接 WebSocket 失败')
    },
  },
})

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

heartbeat

通常的做法是每隔一段时间发送一个小消息(心跳)以保持连接活跃。在这个函数中,我们提供了一个方便的辅助函数来实现这一点:

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

或者进行更多控制:

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

子协议

要使用的子协议列表,在这个例子中是 soap 和 wamp。

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

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

Type Declarations

Show Type Declarations
typescript
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>

Source

SourceDocs

Contributors

Anthony Fu
IlyaL
Fernando Fernández
丶远方
Anthony Fu
Ivan Demidov
Shinigami
freakbite
Dan Rose
Antério Vieira
Antoine Lassier
Vida Xie
Robin
RT
SnowGuest
James Garbutt
lavolpecheprogramma
HengJing Wang
Evan
Vanweiping
alipay404
shanyi-front
Johann Kellerman
Dan Rose
cn.shperry
azaleta
Mikhailov Nikita
Jelf
Ernest
Roland Doda
Shangbu Li
webfansplz
Jan-Henrik Damaschke
Joacim de la Motte
Alex Kozack
iGalaxyz

Changelog

7432f - feat(types): deprecate MaybeRef and MaybeRefOrGetter in favor of Vue's native (#4636)
9ba07 - fix: don't call close() on pongTimeout if connection al… (#4608)
73e6d - feat: pass the retried to the autoReconnect.retries (#4604)
dd316 - feat: use passive event handlers everywhere is possible (#4477)
59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
230f8 - feat(useEventSource): new autoConnect option to align with useWebSocket (#4204)
ffa00 - fix: clear retryTimer when connected (#4383)
ece6a - fix: close socket connection inside WebWorker fix (#4229)
05e75 - feat: introduce autoConnect options to control auto connections on url changes (#4417)
a72c0 - feat(useWebsocket): support ref or getter as message (#4116)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
08412 - fix: autoreconnect when ws close (#4314)
3c2fc - fix: should reset retry count when connection is established (#4164)
e0e99 - fix: only reconnect if is the current ws socket (#4161)
adbe0 - feat: allow different heartbeat response message (#3950)
c2f92 - fix: urlRef changes were not being tracked (#3870)
93b96 - fix: immediate should only be applied once, close #3676
9a47a - fix: reset wsRef on close, fix #3706 (#3707)
9b014 - fix: webworker support (#3469)
c3a69 - fix: ssr support (#3370)
aea27 - fix(useWebsocket): reset pongTimeout on close (#3324)
93372 - fix(useWebsocket): pongTimeout auto-reconnect no work (#3321)
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
10e98 - feat(toRef)!: rename resolveRef to toRef

Released under the MIT License.