跳到主要內容

useWebSocket

Category
匯出大小
1.44 kB
Last Changed
5 days ago

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

Enable by default.

Establish the connection immediately when the composable is called.

autoConnect

Enable by default.

If url is provided as a ref, when the url changes, it will automatically reconnect to the new url.

autoClose

Enable by default.

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

autoReconnect

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')
    },
  },
})

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

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']
})

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.dev.org.tw/useWebSocket
 * @param url
 */
export declare function useWebSocket<Data = any>(
  url: MaybeRefOrGetter<string | URL | undefined>,
  options?: UseWebSocketOptions,
): UseWebSocketReturn<Data>

Source

原始碼文件

貢獻者

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

更新日誌

v12.8.0 於 2025/3/5
7432f - feat(types): 棄用 MaybeRefMaybeRefOrGetter,改用 Vue 原生語法 (#4636)
9ba07 - fix: 如果連線已…,則不在 pongTimeout 時呼叫 close() (#4608)
73e6d - feat: 將 retried 傳遞給 autoReconnect.retries (#4604)
v12.4.0 於 2025/1/10
dd316 - feat: 在任何可能的地方使用被動事件處理器 (#4477)
v12.3.0 於 2025/1/2
59f75 - feat(toValue): 棄用 @vueuse/shared 中的 toValue,改用 Vue 原生語法
v12.2.0-beta.1 於 2024/12/23
230f8 - feat(useEventSource): 新增 autoConnect 選項,與 useWebSocket 對齊 (#4204)
ffa00 - fix: 連線時清除 retryTimer (#4383)
v12.1.0 於 2024/12/22
ece6a - fix: 在 WebWorker 修正中關閉 socket 連線 (#4229)
05e75 - feat: 引入 autoConnect 選項以控制 url 變更時的自動連線 (#4417)
a72c0 - feat(useWebsocket): 支援 ref 或 getter 作為訊息 (#4116)
v12.0.0-beta.1 於 2024/11/21
0a9ed - feat!: 移除 Vue 2 支援,最佳化 bundle 並清理 (#4349)
v11.2.0 於 2024/10/30
08412 - fix: ws 關閉時自動重新連線 (#4314)
v11.0.2 於 2024/8/24
3c2fc - fix: 建立連線時應重設重試計數 (#4164)
e0e99 - fix: 僅在目前的 ws socket 時重新連線 (#4161)
v11.0.0-beta.2 於 2024/7/17
adbe0 - feat: 允許不同的心跳回應訊息 (#3950)
v10.10.0 於 2024/5/27
c2f92 - fix: urlRef 變更未被追蹤 (#3870)
v10.8.0 於 2024/2/20
93b96 - fix: immediate 應僅套用一次,關閉 #3676
9a47a - fix: 在關閉時重設 wsRef,修正 #3706 (#3707)
v10.6.0 於 2023/11/9
9b014 - fix: webworker 支援 (#3469)
v10.5.0 於 2023/10/7
c3a69 - fix: ssr 支援 (#3370)
v10.4.0 於 2023/8/25
aea27 - fix(useWebsocket): 在關閉時重設 pongTimeout (#3324)
93372 - fix(useWebsocket): pongTimeout 自動重新連線無法運作 (#3321)
v10.0.0-beta.4 於 2023/4/13
4d757 - feat(types)!: 將 MaybeComputedRef 重新命名為 MaybeRefOrGetter
10e98 - feat(toRef)!: 將 resolveRef 重新命名為 toRef
v9.12.0 於 2023/1/29
13924 - feat: 允許未定義的 ref 作為 url (#2473)

在 MIT 許可證下發布。