yy-sse-client
v1.0.0
Published
SSE (Server-Sent Events) 客户端工具
Maintainers
Readme
yy-sse-client
SSE (Server-Sent Events) 客户端工具。
安装
npm install yy-sse-client使用
import SSEClient from 'yy-sse-client';
// 创建 SSE 客户端实例
const sseClient = new SSEClient(
'/api/events', // endpoint
{ userId: '123' }, // 查询参数
(event) => { // 消息处理回调
console.log('收到消息:', event.data);
},
{ // 可选配置
headers: {
'Authorization': 'Bearer token'
}
}
);
// 初始化连接
await sseClient.init();
// 检查连接状态
if (sseClient.isConnected()) {
console.log('已连接');
}
// 关闭连接
sseClient.close();在 Vue 组件中使用
<script setup>
import { onMounted, onUnmounted } from 'vue';
import SSEClient from 'yy-sse-client';
let sseClient = null;
onMounted(() => {
sseClient = new SSEClient(
'/api/chat/stream',
{ conversationId: '123' },
(event) => {
// 处理消息
const data = JSON.parse(event.data);
console.log(data);
}
);
sseClient.init();
});
onUnmounted(() => {
if (sseClient) {
sseClient.close();
}
});
</script>API
SSEClient 类
构造函数
new SSEClient(endpoint, params, onMessage, options)参数:
endpoint(string) - SSE 端点 URLparams(object) - 查询参数对象onMessage(Function) - 消息处理回调函数options(object) - 可选配置method(string) - HTTP 方法,默认 "GET"openWhenHidden(boolean) - 页面隐藏时保持连接,默认 trueheaders(object) - 请求头- 其他
fetchEventSource支持的选项
方法
init()- 初始化 SSE 连接close()- 关闭 SSE 连接isConnected()- 检查连接状态buildUrl()- 构建完整的 URL(内部方法)
特性
- ✅ 基于 @microsoft/fetch-event-source
- ✅ 支持查询参数
- ✅ 自动重连(由 fetch-event-source 处理)
- ✅ 可配置选项
- ✅ TypeScript 支持
