* 处理 WebSocket 连接
(ws: WebSocket, request: any)
| 103 | * 处理 WebSocket 连接 |
| 104 | */ |
| 105 | private handleConnection(ws: WebSocket, request: any): void { |
| 106 | const clientId = `client-${Date.now()}-${Math.random()}`; |
| 107 | this.clients.set(clientId, ws); |
| 108 | |
| 109 | console.log(`Client connected: ${clientId}`); |
| 110 | |
| 111 | ws.on('message', async data => { |
| 112 | try { |
| 113 | const message = JSON.parse(data.toString()); |
| 114 | await this.handleMessage(clientId, message); |
| 115 | } catch (error) { |
| 116 | this.sendError(clientId, -32700, 'Parse error', error); |
| 117 | } |
| 118 | }); |
| 119 | |
| 120 | ws.on('close', () => { |
| 121 | this.clients.delete(clientId); |
| 122 | console.log(`Client disconnected: ${clientId}`); |
| 123 | }); |
| 124 | |
| 125 | ws.on('error', error => { |
| 126 | console.error(`WebSocket error for ${clientId}:`, error); |
| 127 | this.clients.delete(clientId); |
| 128 | }); |
| 129 | } |
| 130 | |
| 131 | /** |
| 132 | * 处理 Stdio 连接 |