Files
node-mir-server/GateServer/index.js
Kubbo 002e7214ce feat(server): 添加数据处理模块并增强服务器功能
- 新增 DataProcesser 类,用于处理数据包和管理会话
- 在 GateServer 中添加客户端管理、广播消息和服务器停止功能
- 优化 GateServer 的连接处理逻辑,增加客户端 ID 和信号处理
2025-04-10 07:23:02 +08:00

75 lines
2.2 KiB
JavaScript

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;