const http = require('http'); const path = require('path'); require('dotenv').config({ path: path.join(__dirname, '.env') }); require('dotenv').config({ path: path.join(__dirname, '..', '.env') }); const { Server } = require('socket.io'); const { createClient } = require('redis'); const { log } = require('./src/utils'); const redisUrl = process.env.REDIS_URL || 'redis://127.0.0.1:6379'; const gatewayPort = Number(process.env.WS_GATEWAY_PORT || 3001); const corsOrigin = process.env.WS_GATEWAY_CORS_ORIGIN || '*'; const server = http.createServer(); const io = new Server(server, { cors: { origin: corsOrigin, methods: ["GET", "POST"] } }); const subscriber = createClient({ url: redisUrl }); subscriber.on('error', (err) => { log('Redis', `订阅异常: ${err.message}`); }); function safeParseJson(input) { try { return JSON.parse(input); } catch { return {}; } } async function start() { await subscriber.connect(); await Promise.all([ subscriber.pSubscribe('bot-log-*', (message, channel) => { io.emit(channel, safeParseJson(message)); }), subscriber.pSubscribe('bot-status-*', (message, channel) => { io.emit(channel, safeParseJson(message)); }), subscriber.pSubscribe('bot-error-*', (message, channel) => { io.emit(channel, safeParseJson(message)); }) ]); io.on('connection', (socket) => { log('Gateway', `Client connected: ${socket.id}`); socket.on('disconnect', () => { log('Gateway', `Client disconnected: ${socket.id}`); }); }); server.listen(gatewayPort, () => { log('Gateway', `WS Gateway running on http://localhost:${gatewayPort}`); }); } start().catch((err) => { log('Gateway', `启动失败: ${err.message}`); process.exit(1); });