* 建立 WebSocket 连接 * @returns Promise that resolves when connected
()
| 160 | * @returns Promise that resolves when connected |
| 161 | */ |
| 162 | private async connectWs(): Promise<void> { |
| 163 | // 如果已经连接或正在连接,直接返回 |
| 164 | if (this.ws && this.ws.readyState === WebSocket.OPEN) { |
| 165 | return; |
| 166 | } |
| 167 | |
| 168 | if (this.wsConnecting) { |
| 169 | // 等待连接完成 |
| 170 | return new Promise((resolve, reject) => { |
| 171 | const checkInterval = setInterval(() => { |
| 172 | if (!this.wsConnecting) { |
| 173 | clearInterval(checkInterval); |
| 174 | if (this.ws && this.ws.readyState === WebSocket.OPEN) { |
| 175 | resolve(); |
| 176 | } else { |
| 177 | reject(new NetworkError('WebSocket connection failed')); |
| 178 | } |
| 179 | } |
| 180 | }, 100); |
| 181 | |
| 182 | // 10秒超时 |
| 183 | setTimeout(() => { |
| 184 | clearInterval(checkInterval); |
| 185 | reject(new TimeoutError('WebSocket connection timeout', 10000)); |
| 186 | }, 10000); |
| 187 | }); |
| 188 | } |
| 189 | |
| 190 | this.wsConnecting = true; |
| 191 | |
| 192 | return new Promise((resolve, reject) => { |
| 193 | try { |
| 194 | // 将 http:// 或 https:// 转换为 ws:// 或 wss:// |
| 195 | let wsUrl = this.config.host; |
| 196 | if (wsUrl.startsWith('http://')) { |
| 197 | wsUrl = wsUrl.replace('http://', 'ws://'); |
| 198 | } else if (wsUrl.startsWith('https://')) { |
| 199 | wsUrl = wsUrl.replace('https://', 'wss://'); |
| 200 | } else if (!wsUrl.startsWith('ws://') && !wsUrl.startsWith('wss://')) { |
| 201 | wsUrl = 'ws://' + wsUrl; |
| 202 | } |
| 203 | |
| 204 | // 创建 WebSocket 连接 |
| 205 | const headers: any = {}; |
| 206 | if (this.config.apiKey) { |
| 207 | headers['Authorization'] = `Bearer ${this.config.apiKey}`; |
| 208 | } |
| 209 | |
| 210 | this.ws = new WebSocket(wsUrl, { headers }); |
| 211 | |
| 212 | // 连接成功 |
| 213 | this.ws.on('open', () => { |
| 214 | this.wsConnecting = false; |
| 215 | this.wsReconnectAttempts = 0; |
| 216 | if (process.env.NODE_ENV !== 'test') { |
| 217 | console.log(`WebSocket connected to ${wsUrl}`); |
| 218 | } |
| 219 | resolve(); |
no test coverage detected