export default class WSClient { constructor(options) { // 基础配置 this.url = options.url; this.timeout = options.timeout || 60000; this.headers = { ...options.headers }; // 状态管理 this.ws = null; this.isConnected = false; this.fullThinking = ''; this.fullAnswer = ''; this.timeoutId = null; // 事件回调 this.callbacks = { open: [], close: [], error: [], start: [], status: [], thinking: [], answer: [], finish: [] }; } // 注册事件监听 on(event, callback) { if (this.callbacks[event]) { this.callbacks[event].push(callback); } else { console.warn(`未知事件类型: ${event}`); } } // 触发事件 emit(event, data) { if (this.callbacks[event]) { this.callbacks[event].forEach(callback => { try { callback({ ...data, timestamp: Date.now() }); } catch (e) { console.error(`事件${event}回调错误:`, e); } }); } } // 建立连接 open(data) { // 关闭现有连接 this.close(); // 重置状态 this.fullThinking = ''; this.fullAnswer = ''; try { // 创建 WebSocket 连接 this.ws = uni.connectSocket({ url: this.url, header: this.headers, complete: () => { // 连接完成回调 } }); // uni.connectSocket 是异步的,需要在 success 回调中处理 this.ws.onOpen((res) => { clearTimeout(this.timeoutId); this.isConnected = true; this.emit('open', { res }); // 连接建立后发送数据 // if (data) { // this.send(data); // } }); this.ws.onMessage((res) => { console.log('接收到数据:', res,); let segmentText = ''; try { // 先检查数据是否为字符串 if (typeof res.data === 'string' && res.data.trim().startsWith('{') || res.data.trim().startsWith('[')) { // 只有看起来像JSON的字符串才尝试解析 const parsedData = JSON.parse(res.data); segmentText = parsedData.text || parsedData.message || JSON.stringify(parsedData); } else { // 直接使用原始数据 segmentText = res.data; } } catch (e) { console.error('JSON解析错误:', e, '原始数据:', res.data); // 解析失败,直接使用原始数据 segmentText = res.data; } console.log('处理后的文本段:', segmentText); this.emit('answer', { segment: segmentText, }); }); this.ws.onError((error) => { clearTimeout(this.timeoutId); this.emit('error', { type: 'ws.onError', message: error.errMsg || '连接错误' }); }); this.ws.onClose((res) => { console.log('ws连接已关闭:', res); this.emit('close', { type: 'ws.onClose', reason: res.reason || '连接关闭', code: res.code }); clearTimeout(this.timeoutId); this.isConnected = false; }); // 设置连接超时 // this.timeoutId = setTimeout(() => { // if (!this.isConnected) { // this.emit('error', { type: 'timeout', message: '连接超时' }); // this.close(); // } // }, this.timeout); } catch (error) { clearTimeout(this.timeoutId); this.emit('error', { type: 'init-try-catch', message: error.message || '初始化错误' }); } } // 发送数据 send(data) { console.log('ws发送数据:', data); if (this.ws && this.isConnected) { this.ws.send({ data: JSON.stringify(data), success: (res) => { // 发送成功 console.log('ws发送成功:', res); }, fail: (err) => { this.emit('error', { type: 'send', message: '发送失败: ' + err.errMsg }); } }); } else { this.emit('error', { type: 'send', message: '连接未建立' }); } } // 关闭连接 close(reason) { if (this.ws) { this.ws.close({ success: () => { // 关闭成功 }, fail: (err) => { console.error('关闭连接失败:', err); } }); this.ws = null; } this.isConnected = false; clearTimeout(this.timeoutId); if (reason) { this.emit('close', { reason }); } } }