const net = require('net'); const EventEmitter = require('events'); class GateServer extends EventEmitter { constructor(port, host) { super(); this.port = port; this.host = host; this.server = net.createServer(this.handleConnection.bind(this)); this.clients = new Map(); // 用于存储连接的客户端 this.gateEngineRunning = true; } start() { this.server.listen(this.port, this.host, () => { console.log(`GateServer is listening on ${this.host}:${this.port}`); }); // 处理信号 process.on('SIGINT', () => this.signalHandler('SIGINT')); process.on('SIGTERM', () => this.signalHandler('SIGTERM')); } signalHandler(signal) { if (signal === 'SIGINT' || signal === 'SIGTERM') { this.gateEngineRunning = false; console.log(`[SIGNAL] ${signal} received, shutting down...`); this.stop(); } } handleConnection(socket) { const clientId = `${socket.remoteAddress}:${socket.remotePort}`; console.log(`New client connected: ${clientId}`); this.clients.set(clientId, socket); // 存储客户端连接 this.emit('connection', socket); socket.on('data', (data) => { this.emit('data', socket, data); }); socket.on('end', () => { console.log(`Client disconnected: ${clientId}`); this.clients.delete(clientId); // 移除断开的客户端 this.emit('end', socket); }); socket.on('error', (err) => { console.error(`Socket error for client ${clientId}:`, err); this.clients.delete(clientId); // 移除出错的客户端 this.emit('error', err); }); } // 新增方法:获取当前连接的客户端数量 getClientCount() { return this.clients.size; } // 新增方法:向所有客户端广播消息 broadcast(message) { this.clients.forEach((client) => { client.write(message); }); } // 新增方法:停止服务器 stop() { this.server.close(() => { console.log('GateServer has been stopped.'); }); } } module.exports = GateServer;