| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175 |
- 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 });
- }
- }
- }
|