()
| 18 | } |
| 19 | |
| 20 | export function useWebSocket() { |
| 21 | const connect = async (url: string) => { |
| 22 | if (wsInstance && connectionUrl.value === url) { |
| 23 | console.log("♻️ Reusing existing WebSocket connection"); |
| 24 | return wsInstance; |
| 25 | } |
| 26 | |
| 27 | if (wsInstance) { |
| 28 | console.log("🔄 Disconnecting old WebSocket"); |
| 29 | wsInstance.disconnect(); |
| 30 | } |
| 31 | |
| 32 | console.log("🔌 Creating new WebSocket connection to:", url); |
| 33 | |
| 34 | wsInstance = new WebSocketClient({ |
| 35 | maxReconnectAttempts: 5, |
| 36 | reconnectDelay: 1000, |
| 37 | heartbeatInterval: 30000, |
| 38 | }); |
| 39 | |
| 40 | // 监听状态变化 |
| 41 | wsInstance.onStateChange((state) => { |
| 42 | console.log("📡 WebSocket state changed:", state); |
| 43 | isConnected.value = state === "CONNECTED"; |
| 44 | }); |
| 45 | |
| 46 | await wsInstance.connect(url); |
| 47 | connectionUrl.value = url; |
| 48 | isConnected.value = true; |
| 49 | |
| 50 | console.log("✅ WebSocket connected successfully"); |
| 51 | |
| 52 | return wsInstance; |
| 53 | }; |
| 54 | |
| 55 | const disconnect = () => { |
| 56 | if (wsInstance) { |
| 57 | wsInstance.disconnect(); |
| 58 | wsInstance = null; |
| 59 | isConnected.value = false; |
| 60 | connectionUrl.value = ""; |
| 61 | } |
| 62 | }; |
| 63 | |
| 64 | const getInstance = () => wsInstance; |
| 65 | |
| 66 | return { |
| 67 | connect, |
| 68 | disconnect, |
| 69 | getInstance, |
| 70 | isConnected, |
| 71 | }; |
| 72 | } |
no outgoing calls
no test coverage detected