* 连接到 WebSocket 服务器
(url: string)
| 70 | * 连接到 WebSocket 服务器 |
| 71 | */ |
| 72 | async connect(url: string): Promise<void> { |
| 73 | if (this.state === WebSocketState.CONNECTED || this.state === WebSocketState.CONNECTING) { |
| 74 | console.warn("[WebSocket] Already connected or connecting"); |
| 75 | return; |
| 76 | } |
| 77 | |
| 78 | this.url = url; |
| 79 | this.setState(WebSocketState.CONNECTING); |
| 80 | |
| 81 | return new Promise((resolve, reject) => { |
| 82 | try { |
| 83 | // 在浏览器和 Node.js 中使用不同的 WebSocket |
| 84 | const WebSocketImpl = typeof window !== "undefined" ? window.WebSocket : require("ws"); |
| 85 | |
| 86 | this.ws = new WebSocketImpl(url); |
| 87 | |
| 88 | if (this.ws) { |
| 89 | this.ws.onopen = () => { |
| 90 | console.log("[WebSocket] Connected"); |
| 91 | this.setState(WebSocketState.CONNECTED); |
| 92 | this.reconnectAttempts = 0; |
| 93 | this.startHeartbeat(); |
| 94 | this.flushMessageQueue(); |
| 95 | resolve(); |
| 96 | }; |
| 97 | |
| 98 | this.ws.onmessage = (event) => { |
| 99 | this.handleMessage(event.data); |
| 100 | }; |
| 101 | |
| 102 | this.ws.onerror = (error) => { |
| 103 | console.error("[WebSocket] Error:", error); |
| 104 | reject(error); |
| 105 | }; |
| 106 | |
| 107 | this.ws.onclose = (event) => { |
| 108 | console.log("[WebSocket] Closed:", event.code, event.reason); |
| 109 | this.stopHeartbeat(); |
| 110 | |
| 111 | if (this.state !== WebSocketState.DISCONNECTING) { |
| 112 | this.handleReconnect(); |
| 113 | } else { |
| 114 | this.setState(WebSocketState.DISCONNECTED); |
| 115 | } |
| 116 | }; |
| 117 | } |
| 118 | } catch (error) { |
| 119 | console.error("[WebSocket] Connection failed:", error); |
| 120 | this.setState(WebSocketState.FAILED); |
| 121 | reject(error); |
| 122 | } |
| 123 | }); |
| 124 | } |
| 125 | |
| 126 | /** |
| 127 | * 断开连接 |
no test coverage detected