File size: 13,204 Bytes
d6bdfb4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 | /**
* WebSocket 管理器 - 为 ControlWave 提供可靠的 WebSocket 连接
*
* 特性:
* - 自动重连
* - 连接状态管理
* - 消息队列(离线时缓存消息)
* - 事件系统
* - 错误处理
*/
class ControlWaveWebSocketManager {
constructor(options = {}) {
// 配置选项
this.options = {
url: options.url || `ws://localhost:8080/ws`,
reconnectInterval: options.reconnectInterval || 1000, // 初始重连间隔
maxReconnectInterval: options.maxReconnectInterval || 30000, // 最大重连间隔
reconnectDecay: options.reconnectDecay || 1.5, // 重连间隔增长因子
timeoutInterval: options.timeoutInterval || 2000, // 连接超时
maxReconnectAttempts: options.maxReconnectAttempts || null, // null = 无限重试
enableMessageQueue: options.enableMessageQueue !== false, // 启用消息队列
maxQueueSize: options.maxQueueSize || 100, // 最大队列大小
debug: options.debug || false
};
// 状态管理
this.ws = null;
this.forcedClose = false;
this.reconnectAttempts = 0;
this.reconnectTimer = null;
this.messageQueue = [];
// 连接状态
this.readyState = {
CONNECTING: 0,
OPEN: 1,
CLOSING: 2,
CLOSED: 3,
RECONNECTING: 4
};
this.state = this.readyState.CLOSED;
// 事件监听器
this.eventListeners = {
open: [],
close: [],
error: [],
message: [],
reconnecting: [],
reconnect_failed: []
};
// 自动开始连接
this.connect();
}
// 调试日志
log(...args) {
if (this.options.debug) {
console.log('[WebSocketManager]', ...args);
}
}
// 连接 WebSocket
connect() {
if (this.state === this.readyState.OPEN || this.state === this.readyState.CONNECTING) {
this.log('Already connected or connecting');
return;
}
this.log('Connecting to', this.options.url);
this.state = this.readyState.CONNECTING;
this.forcedClose = false;
try {
this.ws = new WebSocket(this.options.url);
this.setupEventHandlers();
// 连接超时处理
const timeout = setTimeout(() => {
if (this.state === this.readyState.CONNECTING) {
this.log('Connection timeout');
this.ws.close();
}
}, this.options.timeoutInterval);
this.ws.addEventListener('open', () => {
clearTimeout(timeout);
});
} catch (error) {
this.log('Connection error:', error);
this.handleReconnect();
}
}
// 设置事件处理器
setupEventHandlers() {
this.ws.onopen = (event) => {
this.log('Connected');
this.state = this.readyState.OPEN;
this.reconnectAttempts = 0;
// 发送队列中的消息
this.flushMessageQueue();
// 触发事件
this.emit('open', event);
// 触发全局事件供其他组件监听
window.dispatchEvent(new CustomEvent('websocket-connected', {
detail: {
timestamp: new Date().toISOString(),
manager: this
}
}));
};
this.ws.onclose = (event) => {
this.log('Disconnected', event.code, event.reason);
this.state = this.readyState.CLOSED;
this.ws = null;
this.emit('close', event);
if (!this.forcedClose) {
this.handleReconnect();
}
};
this.ws.onerror = (event) => {
this.log('Error:', event);
this.emit('error', event);
};
this.ws.onmessage = (event) => {
this.emit('message', event);
};
}
// 处理重连
handleReconnect() {
if (this.forcedClose) {
return;
}
// 检查最大重连次数
if (this.options.maxReconnectAttempts !== null &&
this.reconnectAttempts >= this.options.maxReconnectAttempts) {
this.log('Max reconnection attempts reached');
this.emit('reconnect_failed', {
attempts: this.reconnectAttempts
});
return;
}
this.state = this.readyState.RECONNECTING;
this.reconnectAttempts++;
// 计算重连延迟(指数退避)
const timeout = Math.min(
this.options.reconnectInterval * Math.pow(this.options.reconnectDecay, this.reconnectAttempts - 1),
this.options.maxReconnectInterval
);
this.log(`Reconnecting in ${timeout}ms (attempt ${this.reconnectAttempts})`);
this.emit('reconnecting', {
attempt: this.reconnectAttempts,
delay: timeout
});
this.reconnectTimer = setTimeout(() => {
this.connect();
}, timeout);
}
// 发送消息
send(data) {
const message = typeof data === 'string' ? data : JSON.stringify(data);
if (this.state === this.readyState.OPEN && this.ws) {
try {
this.ws.send(message);
this.log('Sent:', message);
return true;
} catch (error) {
this.log('Send error:', error);
this.queueMessage(message);
return false;
}
} else {
// 连接未就绪,加入队列
this.queueMessage(message);
return false;
}
}
// 消息入队
queueMessage(message) {
if (!this.options.enableMessageQueue) {
this.log('Message dropped (queue disabled):', message);
return;
}
if (this.messageQueue.length >= this.options.maxQueueSize) {
// 移除最旧的消息
this.messageQueue.shift();
this.log('Message queue full, dropping oldest message');
}
this.messageQueue.push(message);
this.log('Message queued:', message);
}
// 发送队列中的消息
flushMessageQueue() {
if (!this.options.enableMessageQueue || this.messageQueue.length === 0) {
return;
}
this.log(`Flushing ${this.messageQueue.length} queued messages`);
while (this.messageQueue.length > 0) {
const message = this.messageQueue.shift();
try {
this.ws.send(message);
} catch (error) {
this.log('Failed to send queued message:', error);
// 将消息放回队列前端
this.messageQueue.unshift(message);
break;
}
}
}
// 关闭连接
close(code = 1000, reason = '') {
this.forcedClose = true;
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
if (this.ws) {
this.ws.close(code, reason);
}
this.state = this.readyState.CLOSED;
this.messageQueue = [];
}
// 事件系统
on(event, callback) {
if (this.eventListeners[event]) {
this.eventListeners[event].push(callback);
}
}
off(event, callback) {
if (this.eventListeners[event]) {
const index = this.eventListeners[event].indexOf(callback);
if (index > -1) {
this.eventListeners[event].splice(index, 1);
}
}
}
emit(event, data) {
if (this.eventListeners[event]) {
this.eventListeners[event].forEach(callback => {
try {
callback(data);
} catch (error) {
console.error('Event listener error:', error);
}
});
}
}
// 获取连接状态
get isConnected() {
return this.state === this.readyState.OPEN;
}
get isReconnecting() {
return this.state === this.readyState.RECONNECTING;
}
// 兼容旧接口
get socket() {
return this.ws;
}
}
// 创建全局实例
if (typeof window !== 'undefined') {
// 创建管理器实例
const wsManager = new ControlWaveWebSocketManager({
debug: true,
enableMessageQueue: true,
maxQueueSize: 50,
reconnectInterval: 1000,
maxReconnectInterval: 10000
});
// 设置消息处理
wsManager.on('message', (event) => {
try {
const data = JSON.parse(event.data);
console.log('📨 收到 WebSocket 消息:', data.type);
// 处理不同类型的消息
switch(data.type) {
case 'viser_status':
console.log('Viser 状态:', data.active ? '活动' : '未活动', '端口:', data.port);
break;
case 'training_visualization_updated':
console.log('训练可视化已更新:', data.status);
break;
case 'plugin_response':
// plugin_response 消息由 sendRequest 的 responseHandler 处理
// 这里只做日志记录
console.log('插件响应:', data.plugin, data.action, data.status);
break;
default:
console.log('未知消息类型:', data.type);
}
} catch (error) {
console.error('处理 WebSocket 消息时出错:', error);
}
});
// 暴露到全局作用域,兼容旧代码
window.controlWaveWebSocket = {
send: (message) => wsManager.send(message),
get socket() { return wsManager.socket; },
get isConnected() { return wsManager.isConnected; },
// 新增:直接访问管理器
manager: wsManager,
// 新增:sendRequest方法
sendRequest: (pluginId, data) => {
const REQUEST_TIMEOUT_MS = 180000; // 3 minutes to accommodate long-running generations
return new Promise((resolve, reject) => {
const requestId = `${pluginId}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
// 准备消息
const message = {
type: 'plugin_message',
plugin: pluginId,
requestId: requestId,
...data
};
// 设置响应监听器
const responseHandler = (event) => {
try {
const response = JSON.parse(event.data);
// 调试日志
if (response.type === 'plugin_response') {
console.log(`🔍 收到插件响应 [${response.plugin}]:`, {
requestId: response.requestId,
expectedId: requestId,
match: response.requestId === requestId,
status: response.status
});
}
if (response.type === 'plugin_response' &&
response.requestId === requestId) {
// 清理监听器
wsManager.off('message', responseHandler);
console.log('✅ 响应匹配,返回数据:', response);
// 处理响应
if (response.status === 'success') {
resolve(response.response || response);
} else {
reject(new Error(response.message || 'Plugin error'));
}
}
} catch (error) {
// 忽略非JSON消息
}
};
// 添加响应监听器
wsManager.on('message', responseHandler);
// 发送消息
wsManager.send(message);
// 设置超时
setTimeout(() => {
wsManager.off('message', responseHandler);
reject(new Error('Request timeout (180s)'));
}, REQUEST_TIMEOUT_MS);
});
}
};
// 在页面卸载时清理
window.addEventListener('beforeunload', () => {
wsManager.close(1001, 'Page unloading');
});
}
|