interface WebSocketOptions { /** 重连间隔(毫秒),默认 3000 */ reconnectInterval?: number; /** 最大重连次数,0 表示无限重试,默认 10 */ maxReconnectAttempts?: number; /** 心跳间隔(毫秒),默认 10000 */ heartbeatInterval?: number; /** 心跳消息内容,默认 "ping" */ heartbeatMsg?: string; } /** * 自定义回调函数类型 */ interface WebSocketCallbacks { /** 连接成功回调 */ onopen?: (event: Event) => void; /** 连接关闭回调 */ onclose?: (event: CloseEvent) => void; /** 连接错误回调 */ onerror?: (event: Event) => void; /** 接收消息回调 */ onmessage?: (event: MessageEvent) => void; /** 达到最大重连次数回调 */ onmaxreconnect?: () => void; } /** * 带自动重连和心跳检测的 WebSocket 类(TS 版本) */ declare class WebSocketUtils implements WebSocketCallbacks { private readonly url; private readonly reconnectInterval; private readonly maxReconnectAttempts; private readonly heartbeatInterval; private readonly heartbeatMsg; private ws; private reconnectAttempts; private isManualClose; private heartbeatTimer; onopen?: (event: Event) => void; onclose?: (event: CloseEvent) => void; onerror?: (event: Event) => void; onmessage?: (event: MessageEvent) => void; onmaxreconnect?: () => void; constructor(url: string, options?: WebSocketOptions); /** * 初始化/重连 WebSocket 连接 */ private connect; /** * 连接成功事件处理 */ private handleOpen; /** * 连接关闭事件处理 */ private handleClose; /** * 连接错误事件处理 */ private handleError; /** * 消息接收事件处理 */ private handleMessage; /** * 调度重连(带指数退避策略) */ private scheduleReconnect; /** * 发送心跳消息 */ private sendHeartbeat; /** * 启动心跳检测 */ private startHeartbeat; /** * 停止心跳检测 */ private stopHeartbeat; /** * 对外暴露:发送消息 * @param data 要发送的消息(支持 string/ArrayBuffer/Blob) */ send(data: string | ArrayBuffer | Blob): void; /** * 对外暴露:手动关闭连接(不会触发重连) * @param code 关闭码(默认 1000,表示正常关闭) * @param reason 关闭原因 */ close(code?: number, reason?: string): void; /** * 辅助方法:获取连接状态文本 */ getReadyStateText(): string; } export default WebSocketUtils;