MCPcopy
hub / github.com/LLOneBot/LuckyLilliaBot / connectWs

Method connectWs

test/onebot11-api-test/core/ApiClient.ts:162–287  ·  view source on GitHub ↗

* 建立 WebSocket 连接 * @returns Promise that resolves when connected

()

Source from the content-addressed store, hash-verified

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();

Callers 2

attemptReconnectMethod · 0.95
callWsMethod · 0.95

Calls 5

attemptReconnectMethod · 0.95
toStringMethod · 0.80
errorMethod · 0.80
parseMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected