mm_socket_server 1.0.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,155 +1,119 @@
1
1
  # mm_socket_server
2
2
 
3
- TCP/UDP 套接字服务器入站适配器模块。继承 [mm_corejs](https://gitee.com/qiuwenwu91/mm_corejs) 的 `Mod` 基类,提供连接管理、消息处理管道与 JSON-RPC 2.0 消息插件,可脱离完整框架独立运行。
3
+ 最薄的 TCP/UDP 套接字服务器入站适配器。继承 `mm_mod` 的 `Mod`,把每条报文直接交给 `mm_event` 的事件管理器处理,不做路由表、不做插件、不加载脚本。
4
4
 
5
5
  - 入口:`index.js`(CommonJS)
6
- - 导出:`SocketServer`(服务器模块)、`MessagePlugin`(JSON-RPC 消息插件)
7
- - 运行时依赖:`mm_corejs`
8
- - 测试覆盖率:100%(`jest.config.js` 四项阈值)
6
+ - 导出:`SocketServer`、`admin`、`socketServerAdmin`
7
+ - 运行时依赖:`mm_mod`、`mm_event`、`mm_corejs`
9
8
 
10
- ## 特性
9
+ ## 消息路径
11
10
 
12
- - **双协议**:`protocol: 'tcp' | 'udp'`,TCP 按连接登记客户端,UDP 按远端地址首见登记。
13
- - **生命周期**:`init`(校验服务器设置)→ `start`(监听)→ `stop`(断开全部连接)→ `dispose`(清空注册表),状态机由 `mm_corejs` 驱动。
14
- - **消息管道**:入站消息经 `Handle` 的 `before / check / main / render` 阶段处理,管道产出 `result` 时自动回发来源客户端;`getHandle()` 可注册业务钩子(echo、鉴权、改写等)。
15
- - **连接管理**:`Store` 登记在线客户端,支持 `send / broadcast / closeClient / listClients(条件查询与分页)/ hasClient / setClientOptions`。
16
- - **JSON-RPC 2.0 插件**:`MessagePlugin` 挂载后接管 RPC 请求,支持请求-响应、通知回推、主动推送与服务器反向调用客户端方法。
17
- - **选项透传**:连接级 `options`(user_id / device_id / agent_id 等)随每条入站消息透传给管道钩子与 RPC 处理函数,适配多用户 / 多设备 / 多智能体场景。
18
-
19
- ## 安装
20
-
21
- ```bash
22
- npm install mm_socket_server
11
+ ```
12
+ net / dgram → connection / message → ctx = { client_id, protocol, address, socket | rinfo }
13
+ → eventManager.run(protocol, params, ctx, options)
14
+ → 结果非空时回发来源客户端
23
15
  ```
24
16
 
25
- ## 环境要求
26
-
27
- - Node.js >= 22.5.0
28
- - 模块规范:CommonJS
17
+ 事件 `target` 取协议名:`tcp` 或 `udp`。`params` 为 `{ client_id, data }`,`data` 在 `json: true` 时尝试 `JSON.parse`(失败回落原文)。
29
18
 
30
19
  ## 快速开始
31
20
 
32
21
  ```js
33
22
  'use strict';
34
23
 
35
- const net = require('net');
36
- const { SocketServer, MessagePlugin } = require('mm_socket_server');
37
-
38
- /** 最小 Server 容器:满足 Base 契约即可(见 example/demo.js 完整实现) */
39
- const server = {
40
- services: new Map(),
41
- getService(name) { return this.services.get(name); },
42
- hasService(name) { return this.services.has(name); },
43
- setService(name, instance) { this.services.set(name, instance); return this; },
44
- getManager() { return undefined; },
45
- hasManager() { return false; }
46
- };
47
-
48
- const socket = new SocketServer({ name: 'socket', host: '127.0.0.1', port: 9100 }, server);
49
-
50
- // 业务钩子:文本消息直接回发 echo
51
- socket.getHandle().on('main', (ctx, params) => `echo: ${params.data}`, 100, 'echo');
24
+ const { SocketServer } = require('mm_socket_server');
52
25
 
53
- // JSON-RPC 插件:登记方法
54
- const rpc = new MessagePlugin();
55
- socket.use(rpc);
56
- rpc.addMethod('sum', (params) => params.reduce((a, b) => a + b, 0));
26
+ const socket = new SocketServer({ name: 'socket', host: '127.0.0.1', port: 9000 });
27
+ const events = socket.getEventManager();
57
28
 
58
- // 事件
59
- socket.on('connection', (client) => socket.setClientOptions(client.id, { user_id: 'u1' }));
60
- socket.on('message', (client_id, data) => console.log(client_id, data));
61
- socket.on('close', (client_id) => console.log('断开', client_id));
62
- socket.on('error', (err) => console.error(err.message));
29
+ events.add({ name: 'echo', target: 'tcp', end: true }).main = async (params, ctx) => ({
30
+ client_id: ctx.client_id,
31
+ data: params.data
32
+ });
63
33
 
64
34
  await socket.init();
65
35
  await socket.start();
66
36
 
67
- // 主动操作
68
- await socket.run({}, { action: 'list' });
69
- await socket.run({}, { action: 'broadcast', data: 'hello all' });
70
-
71
- await socket.stop();
72
- await socket.dispose();
37
+ console.log(socket.getAddress());
73
38
  ```
74
39
 
75
- ## 服务器配置(config)
76
-
77
- 顶层 `config` 字段即服务器设置,`init` 阶段统一校验。
40
+ ## 服务器配置
78
41
 
79
42
  | 字段 | 类型 | 默认值 | 说明 |
80
43
  | --- | --- | --- | --- |
81
- | `name` | string | `'socket'` | 模块名称(必填) |
82
- | `protocol` | `'tcp' \| 'udp'` | `'tcp'` | 传输协议 |
44
+ | `name` | string | `'os'` | 模块名称(必填) |
45
+ | `title` | string | `'Socket服务器模块'` | 模块标题 |
46
+ | `description` | string | — | 模块描述 |
47
+ | `version` | string | `'2.0.0'` | 版本号 |
48
+ | `protocol` | string | `'tcp'` | 传输协议:`tcp` 或 `udp` |
83
49
  | `host` | string | `'0.0.0.0'` | 监听地址 |
84
- | `port` | integer | `9000` | 监听端口(1-65535) |
85
- | `encoding` | `'utf8' \| 'hex' \| 'base64'` | `'utf8'` | 入站数据解码方式 |
86
- | `json` | boolean | `false` | 为 `true` 时入站尝试 JSON 解析(失败回落原文),出站对象自动序列化 |
50
+ | `port` | number | `9000` | 监听端口 |
51
+ | `encoding` | string | `'utf8'` | 入站解码字符集 |
52
+ | `json` | boolean | `false` | 入站尝试 JSON 解析,出站对象自动序列化 |
53
+ | `params` | object | `{ action }` | `main` 的参数约定 |
87
54
 
88
55
  ## API
89
56
 
90
- ### SocketServer
91
-
92
57
  | 成员 | 说明 |
93
58
  | --- | --- |
94
- | `run(ctx, params)` | 主动操作入口,`params.action` 派发:`send`(需 `client_id` / `data`)、`broadcast`(需 `data`)、`close`(需 `client_id`)、`list`(可选 `query` 条件查询) |
59
+ | `init()` / `start()` / `stop()` / `dispose()` | `Mod` 生命周期模板方法 |
60
+ | `onInit()` / `onStart()` / `onStop()` / `onDispose()` | 生命周期钩子,子类可覆盖 |
61
+ | `getEventManager()` | 获取 `mm_event` 的 `socket` 作用域事件管理器(与其他实例共享),用于注册事件 |
62
+ | `setEventManager(manager)` | 注入外部事件管理器,需提供 `run()` |
63
+ | `getAddress()` | 实际监听地址,未启动为 `null` |
64
+ | `run(params, ctx, options)` | 主动操作入口,`params.action` 派发 `send` / `broadcast` / `close` / `list` |
95
65
  | `send(client_id, data)` | 向指定客户端发送数据,返回是否成功 |
96
66
  | `broadcast(data)` | 向全部在线客户端广播,返回送达数 |
97
- | `closeClient(client_id)` | 关闭指定连接,返回是否发起 |
98
- | `listClients(query)` | 在线客户端列表(`{ id, address }`),支持 Store 条件 / 分页 / keyword |
67
+ | `closeClient(client_id)` | 关闭指定客户端(TCP 销毁套接字,UDP 仅移出连接表) |
68
+ | `listClients()` | 在线客户端列表 `{ id, protocol, address }` |
99
69
  | `hasClient(client_id)` | 是否在线 |
100
- | `setClientOptions(client_id, options)` | 绑定连接级选项(`null` 清空),随入站消息透传 |
101
- | `use(plugin)` | 挂载插件(需实现 `bind(server)`) |
102
- | `getHandle()` | 消息管道,注册 `before / check / main / render` 等钩子;钩子产出 `result` 自动回发 |
103
- | `getAddress()` | 实际监听地址,未启动为 `null` |
70
+ | `setClientOptions(client_id, options)` | 绑定连接级选项,随入站消息作为 `options` 透传(`null` 清空) |
104
71
 
105
- ### 事件
72
+ ## 请求上下文(ctx)
106
73
 
107
- | 事件 | 参数 | 触发时机 |
108
- | --- | --- | --- |
109
- | `connection` | `(client)` | 新连接接入(UDP 为首见远端地址) |
110
- | `message` | `(client_id, data)` | 入站消息经管道内置 `emit_message` 钩子分发 |
111
- | `close` | `(client_id)` | 连接关闭 |
112
- | `error` | `(err)` | 底层服务器 / 套接字 / 钩子错误 |
74
+ | 字段 | 说明 |
75
+ | --- | --- |
76
+ | `client_id` | 客户端编号,TCP 形如 `tcp_1`,UDP 形如 `udp_127.0.0.1:5000` |
77
+ | `protocol` | 当前协议,`tcp` 或 `udp` |
78
+ | `address` | 远端地址,形如 `ip:port` |
79
+ | `socket` | TCP 连接(UDP 报文无此字段),事件可直接写出 |
80
+ | `rinfo` | UDP 远端地址信息(TCP 消息无此字段) |
113
81
 
114
- ### 消息管道
82
+ ## 事件处理函数
115
83
 
116
- 每条入站消息以 `{ client_id, data }` 为 `params`、连接级 `options` 为第三参进入管道:
84
+ 签名固定为 `(params, ctx, options)`:
117
85
 
86
+ ```js
87
+ events.add({ name: 'echo', target: 'tcp', end: true }).main = async (params, ctx, options) => {
88
+ return { data: params.data };
89
+ };
118
90
  ```
119
- before → check → main(业务钩子按 sort 依次执行)→ render
120
- ```
121
-
122
- 任一阶段产出非 `undefined` 的 `result` 即回发来源客户端;`check` / `before` 产出时短路后续阶段。
123
91
 
124
- ## MessagePlugin(JSON-RPC 2.0)
92
+ 返回非 `undefined` / `null` 的结果会按 `json` 配置编码后回发来源客户端;返回 `undefined` 则不回发。事件也可直接用 `ctx.socket` 写出。
125
93
 
126
- 挂载后接管 `jsonrpc` 形态消息(非 RPC 消息透传给业务钩子):
94
+ ## 主动操作
127
95
 
128
96
  ```js
129
- const rpc = new MessagePlugin();
130
- socket.use(rpc);
131
- rpc.addMethod('echo', (params, extra, options) => params); // extra.client_id,options 为连接级选项
97
+ await socket.run({ action: 'send', client_id: 'tcp_1', data: 'hi' });
98
+ await socket.run({ action: 'broadcast', data: { type: 'notice' } });
99
+ await socket.run({ action: 'close', client_id: 'tcp_1' });
100
+ await socket.run({ action: 'list' });
132
101
  ```
133
102
 
134
- | 成员 | 说明 |
135
- | --- | --- |
136
- | `addMethod(name, handler)` / `delMethod(name)` / `listMethods(query)` | 方法表管理,处理函数签名 `(params, extra, options)` |
137
- | `push(client_id, data)` | 任意时刻向客户端回推数据(如异步任务完成后) |
138
- | `call(client_id, method, params, options)` | 反向调用客户端方法并等待其反馈,`options.timeout_ms` 缺省 30000 |
139
- | `bind(server)` / `isBound()` | 挂载与状态查询 |
103
+ ## 生命周期
140
104
 
141
- 协议行为:请求(含 `id`)返回响应对象;通知(无 `id`)处理函数有返回值时回推服务器发起的通知 `{ jsonrpc, method, params }`;客户端把响应形态消息(含 `result` / `error`、无 `method`)发回即结算对应的反向调用。
105
+ `onStart` 按 `protocol` 创建并监听 `net.Server` 或 `dgram.Socket`,`onStop` 断开全部连接并关闭服务器。事件管理器取自 `mm_event` 的 `socket` 作用域,由全局 `Admin` 共享,停止时不清理。端口被占用时 `start()` 抛错,模块进入 `error` 状态,可 `dispose()` 释放。
142
106
 
143
107
  ## 示例
144
108
 
145
109
  ```bash
146
- npm run demo # 启动 TCP 演示服务器(127.0.0.1:9100),见 example/demo.js
110
+ npm run demo # 启动演示服务器(127.0.0.1:9000),见 example/demo.js
147
111
  ```
148
112
 
149
113
  ## 测试
150
114
 
151
115
  ```bash
152
- npm test # jest --coverage,四项覆盖率阈值均为 100%
116
+ npm test # node --test
153
117
  ```
154
118
 
155
119
  ## 许可证
@@ -0,0 +1,51 @@
1
+ 'use strict';
2
+
3
+ const { SocketServer } = require('..');
4
+
5
+ /** 演示监听端口 */
6
+ const DEMO_PORT = 9000;
7
+
8
+ /**
9
+ * 注册演示事件:协议名即事件 target
10
+ * @param {Object} events 事件管理器
11
+ * @returns {void}
12
+ */
13
+ function bindEvents(events) {
14
+ events.add({ name: 'echo', target: 'tcp', end: true }).main = async (params, ctx) => ({
15
+ type: 'echo',
16
+ client_id: ctx.client_id,
17
+ data: params.data
18
+ });
19
+
20
+ events.add({ name: 'time', target: 'udp', end: true }).main = async () => ({
21
+ time: new Date().toISOString()
22
+ });
23
+ }
24
+
25
+ /**
26
+ * 演示入口:启动服务器并打印监听地址
27
+ * @returns {Promise<void>} 无返回值
28
+ */
29
+ async function main() {
30
+ const socket = new SocketServer({
31
+ name: 'demo',
32
+ host: '127.0.0.1',
33
+ port: DEMO_PORT,
34
+ protocol: 'tcp'
35
+ });
36
+
37
+ bindEvents(socket.getEventManager());
38
+ socket.on('error', (err) => console.error(`[demo] 错误: ${err.message}`));
39
+
40
+ await socket.init();
41
+ await socket.start();
42
+
43
+ const address = socket.getAddress();
44
+ console.log(`tcp://127.0.0.1:${address.port}`);
45
+ console.log('发送任意内容,结果由 target 为 tcp 的事件返回并自动回发');
46
+ }
47
+
48
+ main().catch((err) => {
49
+ console.error(err);
50
+ process.exit(1);
51
+ });
package/index.js CHANGED
@@ -1,7 +1,6 @@
1
1
  'use strict';
2
2
 
3
3
  const SocketServer = require('./lib/socket');
4
- const MessagePlugin = require('./lib/message');
5
4
  const Admin = require('mm_corejs').Admin;
6
5
 
7
6
  let admin = new Admin();
@@ -9,11 +8,10 @@ admin.setClass(SocketServer);
9
8
 
10
9
  module.exports = {
11
10
  SocketServer,
12
- MessagePlugin,
13
11
  admin,
14
12
  /**
15
13
  * 获取指定作用域的 Socket 服务器
16
- * @param {string} [scope='sys'] 作用域名称
14
+ * @param {string} [scope='os'] 作用域名称
17
15
  * @param {object} [config] 配置参数
18
16
  * @returns {SocketServer} Socket 服务器实例
19
17
  */
@@ -21,6 +19,6 @@ module.exports = {
21
19
  if (!scope) {
22
20
  scope = 'os';
23
21
  }
24
- return admin.get(scope, { name: scope, ...config });
22
+ return admin.get(scope, config);
25
23
  }
26
24
  };
package/lib/socket.js CHANGED
@@ -2,45 +2,23 @@
2
2
 
3
3
  const net = require('net');
4
4
  const dgram = require('dgram');
5
- const { Mod, Store } = require('mm_corejs');
6
- const { Handle } = require('mm_handle');
5
+ const { Mod } = require('mm_mod');
6
+ const { eventAdmin } = require('mm_event');
7
7
 
8
8
  /**
9
- * 服务器设置校验 schema(校验对象为顶层 config,而非 run 时选项)
10
- */
11
- const SERVER_SCHEMA = {
12
- type: 'object',
13
- properties: {
14
- protocol: { type: 'string', enum: ['tcp', 'udp'] },
15
- host: { type: 'string', min_length: 1 },
16
- port: { type: 'integer', minimum: 1, maximum: 65535 },
17
- encoding: { type: 'string', enum: ['utf8', 'hex', 'base64'] },
18
- json: { type: 'boolean' }
19
- }
20
- };
21
-
22
- /**
23
- * SocketServer —— TCP/UDP 套接字服务器(入站适配器模块)。
24
- *
25
- * 继承 mm_corejs 的 Mod:生命周期由 Lifecycle 模板方法驱动,
26
- * 调用参数校验由 config.params 声明式定义;
27
- * 服务器设置(protocol / host / port / encoding / json)为顶层 config 字段,
28
- * 在 onInit 阶段按 SERVER_SCHEMA 统一校验。
9
+ * SocketServer —— 最薄的 TCP/UDP 传输层(入站适配器模块)。
29
10
  *
30
- * 职责:
31
- * 1. 监听:onStart 按 protocol 创建 net.Server 或 dgram.Socket 并监听;
32
- * 2. 连接管理:#clients 使用 Store 登记在线客户端(主键 id,支持条件查询与分页);
33
- * 3. 消息管道:收到的消息经 Handle 的 before/check/main/render 阶段处理,
34
- * 管道产出 result 时自动回发来源客户端;getHandle() 可注册自定义钩子;
35
- * 4. 事件分发:connection / message / close / error 经 EventEmitter 向外广播;
36
- * 5. 主动操作:run(ctx, params) 按 params.action 派发 send / broadcast / close / list。
11
+ * 只做三件事:
12
+ * 1. 生命周期:由 Mod 的 init / start / stop 驱动 net.Server 或 dgram.Socket;
13
+ * 2. 消息转交:以协议名(tcp / udp)为 target,直接调用
14
+ * EventManager.run(target, params, ctx, options),不做路由、不做插件;
15
+ * 3. 结果回发:事件返回非空结果时回发来源客户端,事件也可用 ctx.socket 自行写出。
37
16
  *
38
17
  * 用法:
39
- * const socket = new SocketServer({ name: 'socket', host: '127.0.0.1', port: 9000 }, server);
40
- * socket.getHandle().on('main', (ctx, params) => `echo: ${params.data}`, 100, 'echo');
18
+ * const socket = new SocketServer({ name: 'socket', protocol: 'tcp', port: 9000 });
19
+ * socket.getEventManager().add({ name: 'echo', target: 'tcp' }).main = async (params) => params.data;
41
20
  * await socket.init();
42
21
  * await socket.start();
43
- * await socket.run({}, { action: 'list' });
44
22
  */
45
23
  class SocketServer extends Mod {
46
24
  /**
@@ -49,22 +27,20 @@ class SocketServer extends Mod {
49
27
  static config = {
50
28
  name: 'os',
51
29
  title: 'Socket服务器模块',
52
- description: 'TCP/UDP 套接字服务器,管理连接并分发消息',
53
- version: '1.0.0',
30
+ description: 'TCP/UDP 传输层:消息直达事件管理器,不做路由与插件',
31
+ version: '2.0.0',
54
32
  protocol: 'tcp',
55
33
  host: '0.0.0.0',
56
34
  port: 9000,
57
35
  encoding: 'utf8',
58
36
  json: false,
59
- options: {},
60
37
  params: {
61
38
  type: 'object',
62
39
  required: ['action'],
63
40
  properties: {
64
41
  action: { type: 'string', enum: ['send', 'broadcast', 'close', 'list'] },
65
42
  client_id: { type: 'string', min_length: 1 },
66
- data: {},
67
- query: { type: 'object' }
43
+ data: {}
68
44
  }
69
45
  }
70
46
  };
@@ -75,36 +51,37 @@ class SocketServer extends Mod {
75
51
  #server = null;
76
52
 
77
53
  /**
78
- * 连接注册表:Store 存储,主键 id、名称字段 name
54
+ * 事件管理器(取自 mm_event 的 socket 作用域,与其他实例共享)
79
55
  */
80
- #clients = new Store({ key: 'id', name: 'name' });
56
+ #events = null;
81
57
 
82
58
  /**
83
- * 消息处理管道(before/check/main/render/error/success/after)
84
- * 每个实例独立 Handle,避免多实例共享管道导致钩子泄漏
59
+ * 在线连接表:client_id -> 连接信息
85
60
  */
86
- #handle = new Handle();
61
+ #clients = new Map();
87
62
 
88
63
  /**
89
64
  * 客户端编号自增计数器
90
65
  */
91
66
  #counter = 0;
92
67
 
93
- // ---------- 生命周期钩子 ----------
94
68
  /**
95
- * 初始化钩子:校验服务器设置并装配消息管道
69
+ * 构造函数
70
+ * @param {Object} config 模块配置
71
+ * @param {Object} server 框架实例
96
72
  */
97
- async onInit() {
98
- await this._validateConfig();
99
- this._initHandle();
73
+ constructor(config, server) {
74
+ super(config, server);
75
+ this.#events = eventAdmin('socket');
100
76
  }
101
77
 
78
+ // ---------- 生命周期钩子 ----------
102
79
  /**
103
80
  * 启动钩子:按协议创建底层服务器并开始监听
81
+ * @returns {Promise<void>} 无返回值
104
82
  */
105
83
  async onStart() {
106
- const protocol = this.config.protocol;
107
- if (protocol === 'udp') {
84
+ if (this.config.protocol === 'udp') {
108
85
  await this._startUdp();
109
86
  return;
110
87
  }
@@ -112,20 +89,14 @@ class SocketServer extends Mod {
112
89
  }
113
90
 
114
91
  /**
115
- * 停止钩子:断开全部连接并关闭底层服务器
92
+ * 停止钩子:断开全部连接并关闭服务器(事件管理器与其他实例共享,不清理)
93
+ * @returns {Promise<void>} 无返回值
116
94
  */
117
95
  async onStop() {
118
96
  this._closeAllClients();
119
97
  await this._closeServer();
120
98
  }
121
99
 
122
- /**
123
- * 释放钩子:清空连接注册表
124
- */
125
- async onDispose() {
126
- this.#clients.clear();
127
- }
128
-
129
100
  // ---------- 执行入口 ----------
130
101
  /**
131
102
  * 模块主逻辑:按 action 派发操作
@@ -139,7 +110,7 @@ class SocketServer extends Mod {
139
110
  if (action === 'send') return this._actionSend(params);
140
111
  if (action === 'broadcast') return this._actionBroadcast(params);
141
112
  if (action === 'close') return this._actionClose(params);
142
- return this._actionList(params);
113
+ return this._actionList();
143
114
  }
144
115
 
145
116
  /**
@@ -176,11 +147,42 @@ class SocketServer extends Mod {
176
147
 
177
148
  /**
178
149
  * 执行列出连接操作
179
- * @param {Object} params 调用参数,可含 query 查询条件(Store 条件/分页)
180
150
  * @returns {Object} 操作结果,clients 为在线客户端列表
181
151
  */
182
- _actionList(params) {
183
- return { action: 'list', clients: this.listClients(params.query) };
152
+ _actionList() {
153
+ return { action: 'list', clients: this.listClients() };
154
+ }
155
+
156
+ // ---------- 事件管理器 ----------
157
+ /**
158
+ * 获取事件管理器,用于注册事件
159
+ * @returns {Object} 事件管理器实例
160
+ */
161
+ getEventManager() {
162
+ return this.#events;
163
+ }
164
+
165
+ /**
166
+ * 注入外部事件管理器
167
+ * @param {Object} manager 事件管理器实例
168
+ * @returns {SocketServer} 当前实例
169
+ * @throws {TypeError} manager 不具备 run 方法时
170
+ */
171
+ setEventManager(manager) {
172
+ if (!manager || typeof manager.run !== 'function') {
173
+ throw new TypeError(`${this._label()} manager must provide run()`);
174
+ }
175
+ this.#events = manager;
176
+ return this;
177
+ }
178
+
179
+ /**
180
+ * 获取实际监听地址
181
+ * @returns {Object|null} 监听地址信息,未启动时为 null
182
+ */
183
+ getAddress() {
184
+ const server = this.#server;
185
+ return server ? server.address() : null;
184
186
  }
185
187
 
186
188
  // ---------- 公开操作 ----------
@@ -191,10 +193,9 @@ class SocketServer extends Mod {
191
193
  * @returns {boolean} 是否发送成功
192
194
  */
193
195
  send(client_id, data) {
194
- const client = this.#clients.getById(client_id);
196
+ const client = this.#clients.get(client_id);
195
197
  if (!client) return false;
196
- const payload = this._encodeData(data);
197
- return this._sendToClient(client, payload);
198
+ return this._sendToClient(client, this._encodeData(data));
198
199
  }
199
200
 
200
201
  /**
@@ -205,33 +206,35 @@ class SocketServer extends Mod {
205
206
  broadcast(data) {
206
207
  const payload = this._encodeData(data);
207
208
  let count = 0;
208
- for (const client of this.#clients.list()) {
209
+ for (const client of this.#clients.values()) {
209
210
  if (this._sendToClient(client, payload)) count += 1;
210
211
  }
211
212
  return count;
212
213
  }
213
214
 
214
215
  /**
215
- * 关闭指定客户端连接
216
+ * 关闭指定客户端连接(TCP 销毁套接字,UDP 仅移出连接表)
216
217
  * @param {string} client_id 客户端 ID
217
218
  * @returns {boolean} 是否关闭成功
218
219
  */
219
220
  closeClient(client_id) {
220
- const client = this.#clients.getById(client_id);
221
+ const client = this.#clients.get(client_id);
221
222
  if (!client) return false;
223
+ this.#clients.delete(client_id);
222
224
  if (client.socket) client.socket.destroy();
223
- this.#clients.delById(client_id);
224
- this._safeEmit('close', client_id);
225
225
  return true;
226
226
  }
227
227
 
228
228
  /**
229
- * 列出在线客户端(支持 Store 条件查询与分页)
230
- * @param {Object} query 查询条件,可含 page_now / page_size / keyword
231
- * @returns {Array<Object>} 客户端信息列表,含 id 与 address
229
+ * 列出在线客户端
230
+ * @returns {Array<Object>} 客户端信息列表,含 id、protocol 与 address
232
231
  */
233
- listClients(query) {
234
- return this.#clients.list(query).map((client) => ({ id: client.id, address: client.address }));
232
+ listClients() {
233
+ const list = [];
234
+ for (const client of this.#clients.values()) {
235
+ list.push({ id: client.id, protocol: client.protocol, address: client.address });
236
+ }
237
+ return list;
235
238
  }
236
239
 
237
240
  /**
@@ -240,64 +243,30 @@ class SocketServer extends Mod {
240
243
  * @returns {boolean} 是否在线
241
244
  */
242
245
  hasClient(client_id) {
243
- return !!this.#clients.getById(client_id);
246
+ return this.#clients.has(client_id);
244
247
  }
245
248
 
246
249
  /**
247
- * 绑定连接级选项(如 user_id / device_id / agent_id),入站消息将作为管道 options 透传给钩子与 RPC 处理函数
250
+ * 绑定连接级选项,入站消息将作为 options 透传给事件
248
251
  * @param {string} client_id 客户端 ID
249
252
  * @param {Object|null} options 选项对象,null 时清空
250
253
  * @returns {boolean} 是否设置成功(客户端不在线时失败)
251
254
  */
252
255
  setClientOptions(client_id, options) {
253
- const client = this.#clients.getById(client_id);
256
+ const client = this.#clients.get(client_id);
254
257
  if (!client) return false;
255
258
  client.options = options || null;
256
259
  return true;
257
260
  }
258
261
 
259
262
  /**
260
- * 读取连接级选项,未绑定时返回空对象
261
- * @param {string} client_id 客户端 ID
262
- * @returns {Object} 连接级选项
263
+ * 获取连接级选项(复制一份,避免事件管理器回写)
264
+ * @param {Object} client 连接信息
265
+ * @returns {Object} 选项对象
263
266
  */
264
- _clientOptions(client_id) {
265
- const client = this.#clients.getById(client_id);
266
- if (!client || !client.options) return {};
267
- return client.options;
268
- }
269
-
270
- /**
271
- * 挂载插件:调用 plugin.bind(this),由插件自行向管道注册钩子;
272
- * 如 MessagePlugin 挂载后接管 JSON-RPC 请求
273
- * @param {Object} plugin 具备 bind(server) 方法的插件实例
274
- * @returns {SocketServer} 当前实例
275
- * @throws {TypeError} plugin 不具备 bind 方法时
276
- */
277
- use(plugin) {
278
- if (!plugin || typeof plugin.bind !== 'function') {
279
- throw new TypeError(`${this._label()} plugin must provide bind()`);
280
- }
281
- plugin.bind(this);
282
- return this;
283
- }
284
-
285
- /**
286
- * 获取消息处理管道,供外部注册 before/check/main/render 等钩子;
287
- * 钩子产出 result 时自动回发来源客户端
288
- * @returns {Handle} 消息管道实例
289
- */
290
- getHandle() {
291
- return this.#handle;
292
- }
293
-
294
- /**
295
- * 获取实际监听地址
296
- * @returns {Object|null} 监听地址信息,未启动时为 null
297
- */
298
- getAddress() {
299
- const server = this.#server;
300
- return server ? server.address() : null;
267
+ _clientOptions(client) {
268
+ if (!client.options) return {};
269
+ return { ...client.options };
301
270
  }
302
271
 
303
272
  // ---------- TCP ----------
@@ -330,7 +299,7 @@ class SocketServer extends Mod {
330
299
  }
331
300
 
332
301
  /**
333
- * 登记新的 TCP 连接并绑定事件
302
+ * 登记新的 TCP 连接并绑定回调
334
303
  * @param {Object} socket 套接字实例
335
304
  */
336
305
  _handleConnection(socket) {
@@ -338,40 +307,43 @@ class SocketServer extends Mod {
338
307
  const client_id = `tcp_${this.#counter}`;
339
308
  const client = {
340
309
  id: client_id,
341
- name: client_id,
310
+ protocol: 'tcp',
342
311
  address: this._remoteAddress(socket),
343
312
  socket,
344
- rinfo: null
313
+ rinfo: null,
314
+ options: null
345
315
  };
346
- this.#clients.add(client);
316
+ this.#clients.set(client_id, client);
347
317
  socket.on('data', (buf) => this._handleData(client_id, buf));
348
- socket.on('close', () => this._handleClose(client_id));
318
+ socket.on('close', () => this.#clients.delete(client_id));
349
319
  socket.on('error', (err) => this._emitError(err));
350
- this._safeEmit('connection', client);
351
320
  }
352
321
 
353
322
  /**
354
- * 处理 TCP 收到的数据:解码后进入消息管道,产出 result 时自动回发
323
+ * 处理 TCP 收到的数据:解码后交给事件管理器,返回非空结果时回发来源客户端
355
324
  * @param {string} client_id 客户端 ID
356
325
  * @param {Object} buf 数据缓冲区
357
326
  * @returns {Promise<void>} 无返回值
358
327
  */
359
328
  async _handleData(client_id, buf) {
360
- const decoded = this._decodeData(buf);
361
- const params = { client_id, data: decoded };
362
- const ctx = { client_id };
363
- const done = await this.#handle.run(ctx, params, this._clientOptions(client_id));
364
- if (done.error) this._emitError(done.error);
365
- if (done.result !== undefined) this.send(client_id, done.result);
366
- }
367
-
368
- /**
369
- * 处理 TCP 连接关闭
370
- * @param {string} client_id 客户端 ID
371
- */
372
- _handleClose(client_id) {
373
- const existed = this.#clients.delById(client_id);
374
- if (existed) this._safeEmit('close', client_id);
329
+ const client = this.#clients.get(client_id);
330
+ if (!client) return;
331
+ const params = { client_id, data: this._decodeData(buf) };
332
+ const ctx = {
333
+ client_id,
334
+ protocol: client.protocol,
335
+ address: client.address,
336
+ socket: client.socket
337
+ };
338
+ const options = this._clientOptions(client);
339
+ try {
340
+ const result = await this.#events.run(this.config.protocol, params, ctx, options);
341
+ const error = ctx.error || options.error;
342
+ if (error) this._emitError(error);
343
+ if (result !== undefined && result !== null) this.send(client_id, result);
344
+ } catch (err) {
345
+ this._emitError(err);
346
+ }
375
347
  }
376
348
 
377
349
  /**
@@ -414,31 +386,50 @@ class SocketServer extends Mod {
414
386
  }
415
387
 
416
388
  /**
417
- * 处理 UDP 报文:首见远端地址登记为客户端并触发 connection
389
+ * 处理 UDP 报文:首见远端地址登记为客户端,之后交给事件管理器
418
390
  * @param {Object} buf 数据缓冲区
419
391
  * @param {Object} rinfo 远端地址信息
392
+ * @returns {Promise<void>} 无返回值
420
393
  */
421
- _handleUdpMessage(buf, rinfo) {
394
+ async _handleUdpMessage(buf, rinfo) {
395
+ const client = this._ensureUdpClient(rinfo);
396
+ const params = { client_id: client.id, data: this._decodeData(buf) };
397
+ const ctx = {
398
+ client_id: client.id,
399
+ protocol: client.protocol,
400
+ address: client.address,
401
+ rinfo
402
+ };
403
+ const options = this._clientOptions(client);
404
+ try {
405
+ const result = await this.#events.run(this.config.protocol, params, ctx, options);
406
+ const error = ctx.error || options.error;
407
+ if (error) this._emitError(error);
408
+ if (result !== undefined && result !== null) this.send(client.id, result);
409
+ } catch (err) {
410
+ this._emitError(err);
411
+ }
412
+ }
413
+
414
+ /**
415
+ * 登记 UDP 客户端(同一远端地址复用同一 client_id)
416
+ * @param {Object} rinfo 远端地址信息
417
+ * @returns {Object} 客户端信息
418
+ */
419
+ _ensureUdpClient(rinfo) {
422
420
  const client_id = `udp_${rinfo.address}:${rinfo.port}`;
423
- const is_new = !this.#clients.getById(client_id);
421
+ const existed = this.#clients.get(client_id);
422
+ if (existed) return existed;
424
423
  const client = {
425
424
  id: client_id,
426
- name: client_id,
425
+ protocol: 'udp',
427
426
  address: client_id,
428
427
  socket: null,
429
- rinfo
428
+ rinfo,
429
+ options: null
430
430
  };
431
- if (is_new) {
432
- this.#clients.add(client);
433
- this._safeEmit('connection', client);
434
- }
435
- const decoded = this._decodeData(buf);
436
- const params = { client_id, data: decoded };
437
- const ctx = { client_id };
438
- this.#handle.run(ctx, params, this._clientOptions(client_id)).then((done) => {
439
- if (done.error) this._emitError(done.error);
440
- if (done.result !== undefined) this.send(client_id, done.result);
441
- });
431
+ this.#clients.set(client_id, client);
432
+ return client;
442
433
  }
443
434
 
444
435
  // ---------- 数据编解码 ----------
@@ -486,6 +477,7 @@ class SocketServer extends Mod {
486
477
  */
487
478
  _sendToClient(client, payload) {
488
479
  if (client.socket) {
480
+ if (client.socket.destroyed) return false;
489
481
  client.socket.write(payload);
490
482
  return true;
491
483
  }
@@ -506,10 +498,10 @@ class SocketServer extends Mod {
506
498
  }
507
499
 
508
500
  /**
509
- * 断开全部客户端连接并清空注册表
501
+ * 断开全部客户端连接并清空连接表
510
502
  */
511
503
  _closeAllClients() {
512
- for (const client of this.#clients.list()) {
504
+ for (const client of this.#clients.values()) {
513
505
  if (client.socket) client.socket.destroy();
514
506
  }
515
507
  this.#clients.clear();
@@ -524,31 +516,11 @@ class SocketServer extends Mod {
524
516
  if (!server) return Promise.resolve();
525
517
  this.#server = null;
526
518
  return new Promise((resolve) => {
527
- server.close(resolve);
519
+ server.close(() => resolve());
528
520
  });
529
521
  }
530
522
 
531
523
  // ---------- 校验辅助 ----------
532
- /**
533
- * 装配消息管道:内置 main 钩子负责分发 message 事件(sort 置后,
534
- * 不返回值,业务钩子产出的 result 由 _handleData 统一回发)
535
- */
536
- _initHandle() {
537
- this.#handle.on('main', (params, ctx) => {
538
- this._safeEmit('message', params.client_id, params.data);
539
- }, 1000, 'emit_message');
540
- }
541
-
542
- /**
543
- * 校验顶层 config 中的服务器设置
544
- * @returns {Promise<void>} 无返回值
545
- * @throws {Error} 校验不通过时
546
- */
547
- async _validateConfig() {
548
- const tip = await this._validate(this.config, SERVER_SCHEMA);
549
- if (tip) throw new Error(`${this._label()} invalid config: ${tip}`);
550
- }
551
-
552
524
  /**
553
525
  * 断言调用参数含 client_id
554
526
  * @param {Object} params 调用参数
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mm_socket_server",
3
- "version": "1.0.2",
4
- "description": "TCP/UDP 套接字服务器入站适配器模块,继承 mm_corejs 的 Mod 基类,支持独立运行。",
3
+ "version": "2.0.0",
4
+ "description": "最薄的 TCP/UDP 套接字服务器入站适配器:消息直达 mm_event 事件管理器,不做路由与插件。",
5
5
  "keywords": [
6
6
  "超级美眉",
7
7
  "入站适配器",
@@ -22,7 +22,8 @@
22
22
  "main": "index.js",
23
23
  "files": [
24
24
  "index.js",
25
- "lib"
25
+ "lib",
26
+ "example"
26
27
  ],
27
28
  "engines": {
28
29
  "node": ">=22.5.0"
@@ -38,12 +39,11 @@
38
39
  "scripts": {
39
40
  "start": "node example/demo.js",
40
41
  "demo": "node example/demo.js",
41
- "test": "jest --coverage"
42
+ "test": "node --test \"test/*.test.js\""
42
43
  },
43
44
  "dependencies": {
44
- "mm_corejs": "^1.1.4"
45
- },
46
- "devDependencies": {
47
- "jest": "^30.5.2"
45
+ "mm_corejs": "^1.1.4",
46
+ "mm_event": "^2.2.2",
47
+ "mm_mod": "^1.0.1"
48
48
  }
49
49
  }
package/lib/message.js DELETED
@@ -1,150 +0,0 @@
1
- 'use strict';
2
-
3
- const { JsonRpc } = require('mm_corejs');
4
-
5
- /**
6
- * MessagePlugin —— JSON-RPC 2.0 消息插件(mm_socket_server 的可选业务组件)。
7
- *
8
- * 职责:
9
- * 1. 方法表:内部持有 JsonRpc 核心,addMethod / delMethod / listMethods 登记可调用方法;
10
- * 2. 管道挂载:bind(socket) 后向消息管道注册 main 钩子 "json_rpc"(sort 100,
11
- * 先于内置 emit_message 执行),命中 JSON-RPC 请求时以响应对象作为管道 result,
12
- * 由 SocketServer 自动回发来源客户端;
13
- * 3. 通知回推:通知(无 id)处理函数返回非 undefined 结果时,产出服务器发起的
14
- * 通知对象 { jsonrpc, method, params: result } 回推来源客户端;无结果或出错时
15
- * 不产出;非 JSON-RPC 消息(解析失败、缺 jsonrpc 字段)透传,控制权交还管道;
16
- * 4. 主动推送:push(client_id, data) 委托 SocketServer.send,处理函数或服务器代码
17
- * 可在任意时刻(如异步任务完成后)向指定客户端回推结果;
18
- * 5. 反向调用:call(client_id, method, params, options) 向客户端发起 JSON-RPC 请求
19
- * 并等待其反馈;入站消息为响应形态(含 result/error、无 method)时被优先识别
20
- * 并结算待响应调用,实现服务器实时调用客户端方法;
21
- * 6. 编码适配:json 模式产出对象(由 send 序列化),文本模式字符串原样、其余 JSON 序列化。
22
- *
23
- * 用法:
24
- * const socket = new SocketServer({ name: 'socket', port: 9100, json: true }, server);
25
- * const rpc = new MessagePlugin();
26
- * socket.use(rpc);
27
- * rpc.addMethod('echo', (params) => params);
28
- * await socket.init();
29
- * await socket.start();
30
- */
31
- class MessagePlugin {
32
- /**
33
- * JSON-RPC 协议核心
34
- */
35
- #rpc = new JsonRpc();
36
-
37
- /**
38
- * 已挂载的 SocketServer 实例,未挂载时为 null
39
- */
40
- #server = null;
41
-
42
- /**
43
- * 挂载到 SocketServer 的消息管道,注册内置 main 钩子
44
- * @param {Object} server 具备 getHandle() 的 SocketServer 实例
45
- * @returns {MessagePlugin} 当前实例
46
- * @throws {TypeError} server 不具备 getHandle 方法时
47
- */
48
- bind(server) {
49
- if (!server || typeof server.getHandle !== 'function') {
50
- throw new TypeError('[MessagePlugin] server must provide getHandle()');
51
- }
52
- this.#server = server;
53
- server.getHandle().on('main', (params, ctx, options) => {
54
- return this._execute(params, ctx, options);
55
- }, 100, 'json_rpc');
56
- return this;
57
- }
58
-
59
- /**
60
- * 判断是否已挂载
61
- * @returns {boolean} 是否已挂载到 SocketServer
62
- */
63
- isBound() {
64
- return this.#server !== null;
65
- }
66
-
67
- /**
68
- * 登记 RPC 方法
69
- * @param {string} name 方法名
70
- * @param {Function} handler 处理函数,签名 handler(params, extra, options),extra 含 client_id,options 为管道请求选项
71
- * @returns {MessagePlugin} 当前实例
72
- */
73
- addMethod(name, handler) {
74
- this.#rpc.addMethod(name, handler);
75
- return this;
76
- }
77
-
78
- /**
79
- * 删除 RPC 方法
80
- * @param {string} name 方法名
81
- * @returns {boolean} 是否删除成功
82
- */
83
- delMethod(name) {
84
- return this.#rpc.delMethod(name);
85
- }
86
-
87
- /**
88
- * 列出 RPC 方法(支持 Store 条件查询与分页)
89
- * @param {Object} [query] 查询条件,缺省时列出全部
90
- * @returns {Array<Object>} 方法列表,含 name
91
- */
92
- listMethods(query) {
93
- return this.#rpc.listMethods(query);
94
- }
95
-
96
- /**
97
- * 主动推送:向指定客户端回推数据(可用于异步任务完成后通知)
98
- * @param {string} client_id 目标客户端 ID
99
- * @param {string|Object} data 待推送数据,对象时按编码模式序列化
100
- * @returns {boolean} 是否发送成功
101
- * @throws {Error} 插件尚未挂载到服务器时
102
- */
103
- push(client_id, data) {
104
- if (!this.#server) throw new Error('[MessagePlugin] not bound to a server');
105
- const payload = this._format(data);
106
- return this.#server.send(client_id, payload);
107
- }
108
-
109
- /**
110
- * 实时调用客户端方法:发送 JSON-RPC 请求并等待客户端反馈 result
111
- * @param {string} client_id 目标客户端 ID
112
- * @param {string} method 客户端方法名
113
- * @param {*} [params] 调用参数
114
- * @param {Object} [options] 选项,含 timeout_ms(缺省 30000,0 为不超时)
115
- * @returns {Promise<*>} 客户端反馈的 result;错误响应、送达失败或超时时 reject
116
- * @throws {Error} 插件尚未挂载到服务器时
117
- */
118
- call(client_id, method, params, options = {}) {
119
- if (!this.#server) throw new Error('[MessagePlugin] not bound to a server');
120
- return this.#rpc.call((request) => this.#server.send(client_id, this._format(request)), method, params, options);
121
- }
122
-
123
- /**
124
- * 内置 main 钩子逻辑:优先识别客户端反馈,其次执行 RPC 请求并格式化响应
125
- * @param {Object} ctx 执行上下文
126
- * @param {Object} params 消息参数,含 client_id 与 data
127
- * @param {Object} [options] 管道请求选项(连接级,如 user_id / device_id / agent_id),透传给处理函数
128
- * @returns {Promise<Object|string|undefined>} 响应对象或 JSON 字符串;反馈、透传与无结果通知时为 undefined
129
- */
130
- async _execute(params, ctx, options) {
131
- if (this.#rpc.acceptResponse(params.data)) return undefined;
132
- const extra = { client_id: params.client_id };
133
- const response = await this.#rpc.handle(params.data, extra, options);
134
- if (response === undefined) return undefined;
135
- return this._format(response);
136
- }
137
-
138
- /**
139
- * 按服务器 json 配置格式化数据
140
- * @param {Object|string} data 响应对象或待推送数据
141
- * @returns {Object|string} json 模式返回原值,文本模式字符串原样、其余 JSON 序列化
142
- */
143
- _format(data) {
144
- if (this.#server.config.json) return data;
145
- if (typeof data === 'string') return data;
146
- return JSON.stringify(data);
147
- }
148
- }
149
-
150
- module.exports = MessagePlugin;