MCPcopy Create free account
hub / github.com/NanmiCoder/MediaCrawler / useLogWebSocket

Function useLogWebSocket

webui/src/hooks/useWebSocket.ts:10–111  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

8let connectionCount = 0 // 跟踪连接使用者数量
9
10export function useLogWebSocket() {
11 const addLog = useCrawlerStore((state) => state.addLog)
12 const addLogRef = useRef(addLog)
13
14 // 保持 addLog 引用最新
15 useEffect(() => {
16 addLogRef.current = addLog
17 }, [addLog])
18
19 useEffect(() => {
20 connectionCount++
21
22 const connect = () => {
23 if (globalReconnectTimer) {
24 clearTimeout(globalReconnectTimer)
25 globalReconnectTimer = null
26 }
27
28 // 如果已经连接或正在连接,不重复创建
29 if (globalWs && (globalWs.readyState === WebSocket.OPEN || globalWs.readyState === WebSocket.CONNECTING)) {
30 return
31 }
32
33 const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
34 const host = window.location.host
35 const wsUrl = `${protocol}//${host}/api/ws/logs`
36
37 const ws = new WebSocket(wsUrl)
38 globalWs = ws
39
40 ws.onopen = () => {
41 if (globalWs !== ws) return
42 console.log('WebSocket connected')
43 }
44
45 ws.onmessage = (event) => {
46 if (globalWs !== ws) return
47 if (event.data === 'ping') {
48 ws.send('pong')
49 return
50 }
51 if (event.data === 'pong') {
52 return
53 }
54
55 try {
56 const log: LogEntry = JSON.parse(event.data)
57 if (log.id && log.message) {
58 addLogRef.current(log)
59 }
60 } catch (e) {
61 console.warn('Failed to parse WebSocket message:', event.data)
62 }
63 }
64
65 ws.onclose = () => {
66 if (globalWs !== ws) return
67 console.log('WebSocket disconnected')

Callers 1

MainContentFunction · 0.90

Calls 2

connectFunction · 0.85
closeMethod · 0.45

Tested by

no test coverage detected