UNPKG

mm_os

Version:

MM_OS服务端架构,用于快速构建应用程序,支持网站建设、小程序后台、AI应用、物联网(IOT/AIOT)、游戏服务端等多种场景。

114 lines (100 loc) 2.68 kB
const net = require('net'); const { Adapter } = require('./adapter'); /** * Socket适配器 */ class Socket extends Adapter { static config = { host: '0.0.0.0', port: 8200 }; /** * 构造函数 * @param {object} config 配置对象 * @param {object} parent 父对象 */ constructor(config, parent) { super({ ...Socket.config, ...config }, parent); } } /** * 初始化适配器 * @returns {object} 适配器实例 * @private */ Socket.prototype._init = function () { // 创建TCP服务器 this.web = net.createServer(this._onConn.bind(this)); return this; }; /** * 客户端连接处理 * @param {Socket} socket 客户端socket * @private */ Socket.prototype._onConn = function (socket) { // 生成唯一客户端ID let client_id = `client_${this.genClientId()}`; // 存储客户端连接 this.clients.set(client_id, socket); // 记录连接日志 this.log('info', `客户端连接成功: ${client_id} (${socket.remoteAddress}:${socket.remotePort})`); // 监听数据接收 socket.on('data', (data) => { this.log('debug', `服务器接收 ${client_id} 消息: ${data.toString()}`); this._onMessage(client_id, data.toString()); }); // 监听连接关闭 socket.on('close', () => { this._onClose(client_id); }); // 监听错误事件 socket.on('error', (error) => { this._onError(client_id, error); }); }; /** * 启动适配器 */ Socket.prototype.start = function () { let { host, port } = this.config; this.web.listen(port, host, () => { this.log('info', `启动成功!监听地址:${host}:${port}`); }); // 监听服务器错误 this.web.on('error', (error) => { this.log('error', '启动失败:', error); }); }; /** * 发送消息 * @param {string} client_id 客户端ID * @param {string} message 消息内容 * @returns {boolean} 发送是否成功 * @private */ Socket.prototype._send = function (client_id, message) { let socket = this.clients.get(client_id); if (socket && !socket.destroyed) { socket.write(message); this.log('debug', `服务器向 ${client_id} 发送消息: ${message}`); return true; } else { this.log('warn', `客户端 ${client_id} 不存在或已关闭`); return false; } }; /** * 停止适配器 */ Socket.prototype.stop = function () { // 调用父类的_stop方法 this._stop(); // 关闭服务器 this.web.close(() => { // 清空客户端集合 this.clients.clear(); this.log('info', '服务器已停止'); }); }; exports.Socket = Socket;