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

Function connect

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

Source from the content-addressed store, hash-verified

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')
68 globalWs = null
69 // 只在还有使用者时才重连
70 if (connectionCount > 0) {
71 globalReconnectTimer = setTimeout(connect, 2000)
72 }
73 }
74
75 ws.onerror = (error) => {
76 if (globalWs !== ws) return
77 console.error('WebSocket error:', error)
78 }
79 }

Callers 1

useLogWebSocketFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected