const { Controller } = require('egg'); class PrintController extends Controller { async ws() { const { ctx, app, logger } = this; if (!ctx.websocket) { throw new Error('非法请求'); } const ws = ctx.websocket; console.log('WebSocket 客户端已连接'); // 生成唯一ID const uniqueId = await this.service.base.generateUniqueId(); ctx.uniqueId = uniqueId; // 加入房间 ctx.websocket.room.join(uniqueId); // 将房间 uniqueId 写入 Redis,有效期 300 秒 await app.redis.set(uniqueId, JSON.stringify({ connected: true, createdAt: Date.now(), }), 'EX', 300); console.log(`房间 uniqueId 已写入 Redis: ${uniqueId}`); // ✅ 1. 先声明并启动定时器 const heartbeatTimer = setInterval(async () => { try { // 检查连接是否还在 if (ws.readyState !== 1) { // 1 = OPEN logger.info(`连接 ${uniqueId} 已关闭,停止心跳`); clearInterval(heartbeatTimer); return; } // 刷新主 key 过期时间 await app.redis.expire(uniqueId, 300); logger.info(`刷新过期时间成功,uniqueId: ${uniqueId}`); // 如果有打印机信息,刷新仓库打印机 key if (ctx.print_computer_info) { const warehouseKey = `warehouse:${ctx.print_computer_info.warehouse}:printer:${ctx.print_computer_info.computerId}`; await app.redis.expire(warehouseKey, 300); logger.info(`刷新仓库打印机过期时间: ${warehouseKey}`); } } catch (error) { logger.error(`心跳更新失败,uniqueId: ${uniqueId}`, error); } }, 60000); // 60秒执行一次 // ✅ 2. 将定时器存储在多个地方,确保能正确清理 ctx.state = ctx.state || {}; ctx.state.heartbeatTimer = heartbeatTimer; // 也存储到 ws 对象上,方便在 close 中访问 ws.heartbeatTimer = heartbeatTimer; // 消息处理 ws.on('message', async msg => { if(msg=="ping"){ ws.send("pong"); return; } // method过滤 const method_filter = ['test.ping']; if (method_filter.some(method => msg.includes(method))) { // 过滤掉的方法不做处理 } else { console.log('[收到消息]:', msg); } try { const data = JSON.parse(msg); const servicePath = data.method; const classs = servicePath.split('.'); let systemMethods = ctx.service; // 动态解析服务路径 for (let i = 0; i < classs.length - 1; i++) { const className = classs[i]; if (!systemMethods[className]) { throw new Error(`服务路径 ${className} 不存在`); } systemMethods = systemMethods[className]; } // 检查方法是否存在 const methodName = classs.pop(); if (typeof systemMethods[methodName] !== 'function') { throw new Error(`方法 ${methodName} 不存在于服务 ${servicePath}`); } // 调用服务方法 const result = await systemMethods[methodName](data.data); if (result && result.isBack === false) { return; } console.log(`服务调用成功: ${data.method}`, result); ws.send(JSON.stringify({ type: 'response', method: result?.method || data.method, data: result?.data, message: result?.message || '服务调用成功', })); } catch (e) { console.error(`服务调用失败: ${e.message}`, e); ws.send(JSON.stringify({ type: 'error', message: '服务调用失败', error: e.message, })); } }); // 连接关闭 - 清理定时器 ws.on('close', async (code, reason) => { console.log('连接关闭', code, reason); // ✅ 3. 清理定时器 if (ws.heartbeatTimer) { clearInterval(ws.heartbeatTimer); console.log(`心跳定时器已清理: ${uniqueId}`); } // 从 Redis 中删除 uniqueId await app.redis.del(uniqueId); if (ctx.print_computer_info){ const warehouseKey = `warehouse:${ctx.print_computer_info.warehouse}:printer:${ctx.print_computer_info.computerId}`; await app.redis.del(warehouseKey); console.log(`仓库打印机 key 已从 Redis 删除: ${warehouseKey}`); } console.log(`房间 uniqueId 已从 Redis 删除: ${uniqueId}`); }); // 错误处理 ws.on('error', async (error) => { console.error('WebSocket 错误:', error); // ✅ 4. 清理定时器 if (ws.heartbeatTimer) { clearInterval(ws.heartbeatTimer); console.log(`心跳定时器已清理: ${uniqueId}`); } // 从 Redis 中删除 uniqueId await app.redis.del(uniqueId); if (ctx.print_computer_info){ const warehouseKey = `warehouse:${ctx.print_computer_info.warehouse}:printer:${ctx.print_computer_info.computerId}`; await app.redis.del(warehouseKey); console.log(`仓库打印机 key 已从 Redis 删除: ${warehouseKey}`); } console.log(`房间 uniqueId 已从 Redis 删除: ${uniqueId}`); }); } } module.exports = PrintController;