wujingjing
2025-01-14 d5c759fb1c54679a27c20a3a2ed2c7e082820462
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { onMounted, onUnmounted } from 'vue';
import { SSEClient } from './SSEClient';
import { MAIN_URL } from '/@/constants';
 
// 创建实例
const sseClient = new SSEClient(
    `${MAIN_URL}events`,
 
    {},
    {
        onMessage: (data) => {
            console.log('Received message:', data);
        },
        onError: (error) => {
            console.error('SSE error:', error);
        },
        onOpen: () => {
            console.log('SSE connection opened');
        },
        onClose: () => {
            console.log('SSE connection closed');
        },
        onRetry: (retryCount) => {
            console.log(`Retrying connection (${retryCount})`);
        },
    }
);
 
// 在 Vue 组件中使用
export function useSSE() {
    // 建立连接
    sseClient.connect({});
    
 
    // onMounted(() => {
    //     // 建立连接
    //     sseClient.connect({
    //         userId: 'xxx',
    //         sessionId: 'xxx',
    //     });
    // });
 
    // onUnmounted(() => {
    //     // 断开连接
    //     sseClient.disconnect();
    // });
 
    return {
        isConnected: () => sseClient.isConnected(),
        reconnect: () => sseClient.reconnect(),
        disconnect: () => sseClient.disconnect(),
    };
}