Skip to content

useWebSocket

类别
导出大小
1.57 kB
最近修改
2 days ago

响应式 WebSocket 客户端。

🌐 Reactive WebSocket client.

用法

🌐 Usage

ts
import { 
useWebSocket
} from '@vueuse/core'
const {
status
,
data
,
send
,
open
,
close
,
ws
} =
useWebSocket
('ws://websocketurl')

返回值

🌐 Return Values

属性类型描述
dataRef<any>最新接收的数据
statusRef<'OPEN' | 'CONNECTING' | 'CLOSED'>连接状态
wsRef<WebSocket>WebSocket 实例
send(data, useBuffer?) => boolean发送数据(如果未连接则缓冲)
open() => void打开/重新连接连接
close(code?, reason?) => void关闭连接

回调

🌐 Callbacks

ts
const { 
data
} = useWebSocket('ws://websocketurl', {
onConnected
(
ws
) {
console
.
log
('Connected!')
},
onDisconnected
(
ws
,
event
) {
console
.
log
('Disconnected!',
event
.code)
},
onError
(
ws
,
event
) {
console
.
error
('Error:',
event
)
},
onMessage
(
ws
,
event
) {
console
.
log
('Message:',
event
.data)
}, })

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

🌐 See the Type Declarations for more options.

immediate

默认启用。

🌐 Enable by default.

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

🌐 Establish the connection immediately when the composable is called.

autoConnect

默认启用。

🌐 Enable by default.

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

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

autoClose

默认启用。

🌐 Enable by default.

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

🌐 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).

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

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

🌐 Or with more controls over its behavior:

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

你也可以将一个函数传递给 delay 来根据重试次数计算延迟。这对于实现指数退避非常有用:

🌐 You can also pass a function to delay to calculate the delay based on the number of retries. This is useful for implementing exponential backoff:

ts
const { 
status
,
data
,
close
} =
useWebSocket
('ws://websocketurl', {
autoReconnect
: {
retries
: 5,
// Exponential backoff: 1s, 2s, 4s, 8s, 16s
delay
:
retries
=>
Math
.
min
(1000 * 2 ** (
retries
- 1), 30000),
}, })
ts
const { 
status
,
data
,
close
} =
useWebSocket
('ws://websocketurl', {
autoReconnect
: {
retries
: 5,
// Linear backoff: 1s, 2s, 3s, 4s, 5s
delay
:
retries
=>
retries
* 1000,
}, })

显式调用 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:

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

或者使用更多控件:

🌐 Or with more controls:

ts
const { 
status
,
data
,
close
} =
useWebSocket
('ws://websocketurl', {
heartbeat
: {
message
: 'ping',
scheduler
:
cb
=> useIntervalFn(
cb
, 2000),
pongTimeout
: 1000,
}, })

子协议

🌐 Sub-protocols

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

🌐 List of one or more subprotocols to use, in this case SOAP and WAMP.

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