From bc69a9964e5fffc2acde97a745dff193aff138aa Mon Sep 17 00:00:00 2001 From: "shunfeng.zhou" Date: Sun, 13 Apr 2025 17:32:07 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BF=9E=E6=8E=A5=E6=9C=AC=E5=9C=B0localhost?= =?UTF-8?q?=20websocket=E6=9C=8D=E5=8A=A1=E6=88=90=E5=8A=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/extension/ChatViewProvider.ts | 2 +- webview/src/store/chat.ts | 47 ++----------------------------- 2 files changed, 4 insertions(+), 45 deletions(-) diff --git a/src/extension/ChatViewProvider.ts b/src/extension/ChatViewProvider.ts index 6601903..4789cee 100644 --- a/src/extension/ChatViewProvider.ts +++ b/src/extension/ChatViewProvider.ts @@ -298,7 +298,7 @@ export class ChatViewProvider implements vscode.WebviewViewProvider { indexHtml = indexHtml.replace( '', ` - ` + ` ); } diff --git a/webview/src/store/chat.ts b/webview/src/store/chat.ts index e727086..b871d3a 100644 --- a/webview/src/store/chat.ts +++ b/webview/src/store/chat.ts @@ -72,56 +72,15 @@ export class WebSocketService { // 检查是否有API密钥,如果有则添加为查询参数 if (this.apiKey) { const separator = wsUrl.includes('?') ? '&' : '?'; - wsUrl += `${separator}apiKey=${encodeURIComponent(this.apiKey)}`; + wsUrl += `${separator}api_key=${this.apiKey}`; } - // 检查环境和协议 - // const isVsCodeWebview = typeof window !== 'undefined' && 'acquireVsCodeApi' in window; - const isLocalhost = wsUrl.includes('localhost') || wsUrl.includes('127.0.0.1'); - - // VS Code WebView环境下可能需要wss - // if (isVsCodeWebview && wsUrl.startsWith('ws://')) { - // this.logger('[WebSocketService] 在VS Code WebView中,尝试使用安全WebSocket连接'); - // wsUrl = wsUrl.replace('ws://', 'wss://'); - // } - this.logger(`[WebSocketService] 最终WebSocket URL: ${wsUrl}`); this.socket = new WebSocket(wsUrl); this.setupEventHandlers(); - - // 处理连接失败的情况 - if (isLocalhost) { - // 如果使用localhost失败,尝试使用127.0.0.1 - const fallbackTimeout = setTimeout(() => { - if (this.socket?.readyState !== WebSocket.OPEN) { - this.logger('[WebSocketService] localhost连接超时,尝试使用127.0.0.1'); - - let fallbackUrl; - if (wsUrl.includes('localhost')) { - fallbackUrl = wsUrl.replace('localhost', '127.0.0.1'); - } else if (wsUrl.includes('127.0.0.1')) { - fallbackUrl = wsUrl.replace('127.0.0.1', 'localhost'); - } - - if (fallbackUrl && fallbackUrl !== wsUrl) { - this.logger(`[WebSocketService] 尝试备用连接: ${fallbackUrl}`); - - // 关闭旧连接 - if (this.socket) { - this.socket.close(); - } - - // 尝试新连接 - this.socket = new WebSocket(fallbackUrl); - this.setupEventHandlers(); - } - } - clearTimeout(fallbackTimeout); - }, 3000); // 3秒后如果未连接则尝试备用地址 - } } catch (error) { - this.logger(`[WebSocketService] 连接错误: ${error instanceof Error ? error.message : String(error)}`); - this.emit(WebSocketEvent.ERROR, `连接错误: ${error instanceof Error ? error.message : String(error)}`); + this.logger(`[WebSocketService] 连接失败: ${error}`); + this.emit(WebSocketEvent.ERROR, `连接失败: ${error}`); this.scheduleReconnect(); } }