mm_os
Version:
MM_OS服务端架构,用于快速构建应用程序,支持网站建设、小程序后台、AI应用、物联网(IOT/AIOT)、游戏服务端等多种场景。
146 lines (135 loc) • 3.78 kB
JavaScript
const Koa = require('koa');
const websocket = require('koa-websocket');
const { Adapter } = require('./adapter.js');
/**
* WebSocket适配器
*/
class WebSocket extends Adapter {
static config = {
host: '0.0.0.0',
port: 8300
};
/**
* 构造函数
* @param {object} config 配置对象
* @param {object} parent 父对象
*/
constructor(config, parent) {
super({ ...WebSocket.config, ...config }, parent);
}
}
/**
* 初始化WebSocket适配器
* @param {object} web 应用实例
* @private
*/
WebSocket.prototype._init = function (web) {
// 如果提供了应用实例
if (web) {
// 检查是否已经是websocket实例
if (web.ws) {
// 已经是websocket实例,直接使用
this._web = web;
this.external_app = true;
} else {
// 不是websocket实例,包装它
this._web = websocket(web);
this.external_app = true;
}
} else {
// 没有提供应用实例,创建新的
this._web = websocket(new Koa());
this.external_app = false;
}
this.broker = this._web.ws;
// 简化实现:不设置中间件,在连接时处理
};
/**
* 发送消息
* @private
* @param {string} client_id 客户端ID
* @param {string} message 消息内容
* @returns {boolean} 发送是否成功
*/
WebSocket.prototype._send = function (client_id, message) {
let ws = this.clients.get(client_id);
if (ws && ws.readyState === 1) { // WebSocket.OPEN
ws.send(message);
this.log('debug', `服务器向 ${client_id} 发送消息: ${message}`);
return true;
} else {
this.log('warn', `客户端 ${client_id} 不存在或已关闭`);
return false;
}
};
/**
* 启动WebSocket服务器
* @returns {object|undefined} 服务器实例或undefined
*/
WebSocket.prototype.start = function () {
let {
host,
port
} = this.config;
// 如果没有提供外部app实例,启动自己的服务器
if (!this.external_app) {
return this._web.listen(port, host, () => {
this.log('info', `启动成功!监听地址:ws://127.0.0.1:${port}`);
});
} else {
// 如果提供了外部app实例,只需要记录日志
this.log('info', `启动成功!访问地址:ws://127.0.0.1:${port}`);
}
// 监听服务器错误(仅当是自己创建的服务器时)
if (this._tcp_server && !this.external_app) {
this._tcp_server.on('error', (error) => {
this.log('error', '服务器启动失败:', error);
});
}
};
/**
* 停止Adapter服务器
* @private
*/
WebSocket.prototype._stop = function () {
// 关闭所有客户端连接
for (let [, ws] of this.clients) {
ws.close();
}
};
/**
* 处理消息接收
* @private
* @param {string} client_id 客户端ID
* @param {object} ws WebSocket实例
* @param {string} message 消息内容
*/
WebSocket.prototype._onMessage = function (client_id, ws, message) {
this.log('debug', '收到消息', { client_id: client_id });
};
/**
* 处理连接关闭
* @private
* @param {string} client_id 客户端ID
*/
WebSocket.prototype._onClose = function (client_id) {
this.clients.delete(client_id);
this.log('info', `客户端断开连接: ${client_id}`);
};
/**
* 处理错误事件
* @private
* @param {string} client_id 客户端ID
* @param {Error} error 错误对象
*/
WebSocket.prototype._onError = function (client_id, error) {
this.log('error', `客户端 ${client_id} 发生错误:`, error);
};
/**
* 使用中间件
* @param {Function} middleware 中间件函数
*/
WebSocket.prototype.use = function (middleware) {
this.broker.use(middleware);
};
exports.WebSocket = WebSocket;