MCPcopy Create free account
hub / github.com/APIParkLab/APIPark / useWebSocket

Function useWebSocket

frontend/packages/common/src/hooks/webSocket.ts:9–48  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

7 onError: (event: unknown) => void
8}
9const useWebSocket = () => {
10 const [ws, setWs] = useState<WebSocket | null>()
11
12 // 创建WebSocket连接的方法
13 const createWs = (url: string, { onOpen, onClose, onMessage, onError }: WebSocketHookProps) => {
14 if (ws) {
15 ws.close()
16 }
17
18 const socket = new WebSocket(url)
19 setWs(socket)
20
21 socket.onopen = () => onOpen && onOpen()
22 socket.onclose = () => onClose && onClose()
23 socket.onmessage = (event) => onMessage && onMessage(event)
24 socket.onerror = (error) => onError && onError(error)
25
26 return socket
27 }
28
29 // 提供发送消息的方法
30 const sendMessage = useCallback(
31 (message: string) => {
32 if (ws && ws.readyState === WebSocket.OPEN) {
33 ws.send(message)
34 }
35 },
36 [ws]
37 )
38
39 // 断开连接的方法
40 const disconnectWs = useCallback(() => {
41 if (ws) {
42 ws.close()
43 setWs(null)
44 }
45 }, [ws])
46
47 return { createWs, sendMessage, disconnectWs }
48}
49
50export default useWebSocket

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected