Skip to content

useReactiveSSE

创建响应式 SSE(Server-Sent Events)连接(跨框架实现)

前置依赖

依赖参数

参数名类型说明
deps.EventSourceEventSourceConstructorEventSource 构造函数
deps.setTimeouttypeof setTimeout定时器函数
deps.clearTimeouttypeof clearTimeout清除定时器函数
deps.logFunction可选的日志函数,用于调试

环境要求

  • 浏览器环境: 需要支持 EventSource API
  • Node.js环境: 需要安装 eventsource
bash
npm install eventsource

函数签名

typescript
interface UseReactiveSSEDeps {
  EventSource: EventSourceConstructor
  setTimeout: typeof setTimeout
  clearTimeout: typeof clearTimeout
  log?: (...args: any[]) => void
}

interface UseReactiveSSEOptions {
  withCredentials?: boolean
  immediate?: boolean
  reconnect?: SSEReconnectOptions
  onConnected?: (es: EventSource) => void
  onDisconnected?: (es: EventSource, event: any) => void
  onError?: (es: EventSource, event: any) => void
  onMessage?: (es: EventSource, event: any) => void
}

interface SSEReconnectOptions {
  enabled?: boolean
  delay?: number
  maxRetries?: number
  retryDelayMultiplier?: number
}

interface ReactiveSSEState {
  status: SSEStatus
  data: string | null
  lastEventId: string
  error: Error | null
  retryCount: number
  es: EventSource | null
}

interface ReactiveSSEReturn {
  state: ReactiveSSEState
  connect: () => void
  disconnect: () => void
  addEventListener: (type: string, listener: (event: any) => void) => () => void
  subscribe: (listener: () => void) => () => void
  dispose: () => void
}

function useReactiveSSE(
  url: string,
  options?: UseReactiveSSEOptions,
  deps: UseReactiveSSEDeps
): ReactiveSSEReturn

参数

参数名类型必填说明
urlstringSSE 服务器地址
optionsUseReactiveSSEOptions配置选项
depsUseReactiveSSEDeps环境依赖

UseReactiveSSEOptions 选项

名称类型默认值说明
withCredentialsbooleanfalse是否发送凭证(cookies)
immediatebooleantrue是否立即连接
reconnectSSEReconnectOptions-重连配置
onConnectedFunction-连接成功回调
onDisconnectedFunction-断开连接回调
onErrorFunction-错误回调
onMessageFunction-消息回调

SSEReconnectOptions 重连配置

名称类型默认值说明
enabledbooleantrue是否启用自动重连
delaynumber3000重连延迟(毫秒)
maxRetriesnumber5最大重连次数,0 表示无限重连
retryDelayMultipliernumber1.5重连延迟增长因子

返回值

类型说明
ReactiveSSEReturn响应式 SSE 对象

ReactiveSSEReturn 属性和方法

名称类型说明
stateReactiveSSEState响应式状态对象
connect() => void连接 SSE
disconnect() => void断开连接
addEventListener(type, listener) => () => void添加事件监听器
subscribe(listener: () => void) => () => void订阅状态变化
dispose() => void销毁实例

ReactiveSSEState 状态对象

名称类型说明
statusSSEStatus连接状态:CONNECTING / CONNECTED / DISCONNECTED / ERROR
datastring | null最新接收的数据
lastEventIdstring最后一个事件 ID
errorError | null错误信息
retryCountnumber当前重连次数
esEventSource | nullEventSource 实例

工作原理

  1. 创建响应式状态对象,包含连接状态、接收数据、事件 ID、错误信息等
  2. 根据配置选项创建 EventSource 连接
  3. 监听 EventSource 事件(open、message、error)并更新响应式状态
  4. 支持自动重连,连接错误时自动尝试重连,重连延迟递增
  5. 支持自定义事件监听,可以监听服务器发送的命名事件
  6. 提供 connect/disconnect 方法控制连接
  7. 通过 subscribe 方法监听状态变化
  8. 支持跨框架使用(不依赖 Vue 或其他框架)

SSE vs WebSocket

特性SSE (useReactiveSSE)WebSocket (useReactiveWebsocket)
通信方向单向(服务器→客户端)双向
协议HTTPWebSocket
消息格式文本(UTF-8)文本 / 二进制
浏览器重连自动重连需要手动实现
事件类型支持命名事件统一的 message 事件
复杂度简单较复杂
适用场景实时通知、进度推送聊天、游戏、实时协作