Skip to content
On this page

useWebSocket

用于处理 WebSocket 的 Hook。

代码演示

API

enum ReadyState {
  Connecting = 0,
  Open = 1,
  Closing = 2,
  Closed = 3,
}

interface Options {
  reconnectLimit?: number;
  reconnectInterval?: number;
  onOpen?: (event: WebSocketEventMap['open'], instance: WebSocket) => void;
  onClose?: (event: WebSocketEventMap['close'], instance: WebSocket) => void;
  onMessage?: (message: WebSocketEventMap['message'], instance: WebSocket) => void;
  onError?: (event: WebSocketEventMap['error'], instance: WebSocket) => void;
  protocols?: string | string[];
}

interface Result {
  latestMessage?: WebSocketEventMap['message'];
  sendMessage?: WebSocket['send'];
  disconnect?: () => void;
  connect?: () => void;
  readyState: ReadyState;
  webSocketIns?: WebSocket;
}

useWebSocket(socketUrl: string, options?: Options): Result;
enum ReadyState {
  Connecting = 0,
  Open = 1,
  Closing = 2,
  Closed = 3,
}

interface Options {
  reconnectLimit?: number;
  reconnectInterval?: number;
  onOpen?: (event: WebSocketEventMap['open'], instance: WebSocket) => void;
  onClose?: (event: WebSocketEventMap['close'], instance: WebSocket) => void;
  onMessage?: (message: WebSocketEventMap['message'], instance: WebSocket) => void;
  onError?: (event: WebSocketEventMap['error'], instance: WebSocket) => void;
  protocols?: string | string[];
}

interface Result {
  latestMessage?: WebSocketEventMap['message'];
  sendMessage?: WebSocket['send'];
  disconnect?: () => void;
  connect?: () => void;
  readyState: ReadyState;
  webSocketIns?: WebSocket;
}

useWebSocket(socketUrl: string, options?: Options): Result;

Params

参数说明类型默认值
socketUrl必填,webSocket 地址string-
options可选,连接配置项Options-

Options

参数说明类型默认值
onOpenwebSocket 连接成功回调(event: WebSocketEventMap['open'], instance: WebSocket) => void-
onClosewebSocket 关闭回调(event: WebSocketEventMap['close'], instance: WebSocket) => void-
onMessagewebSocket 收到消息回调(message: WebSocketEventMap['message'], instance: WebSocket) => void-
onErrorwebSocket 错误回调(event: WebSocketEventMap['error'], instance: WebSocket) => void-
reconnectLimit重试次数number3
reconnectInterval重试时间间隔(ms)number3000
manual手动启动连接booleanfalse
protocols子协议string | string[]-

Result

参数说明类型
latestMessage最新消息Ref<WebSocketEventMap['message']>
sendMessage发送消息函数WebSocket['send']
disconnect手动断开 webSocket 连接() => void
connect手动连接 webSocket,如果当前已有连接,则关闭后重新连接() => void
readyState当前 webSocket 连接状态Ref<ReadyState>
webSocketInswebSocket 实例WebSocket

Source

源码文档示例