202 lines
8.5 KiB
JavaScript
202 lines
8.5 KiB
JavaScript
import { WebSocketServer } from 'ws';
|
|
import path from 'path';
|
|
import fs from 'fs';
|
|
import { pathToFileURL } from 'url';
|
|
|
|
class WSServer {
|
|
constructor(port, app, options = {}) {
|
|
this.port = port || 8081;
|
|
this.options = options;
|
|
this.server = null;
|
|
this.clients = new Set();
|
|
this.services = app.services; // 从 app 获取服务实例
|
|
this._start();
|
|
this.app = app;
|
|
app.on('printerComponentStatusChange', (data) => {
|
|
this.broadcast({ success: true, method: 'printerComponent.statusChange', result: data });
|
|
});
|
|
app.on('wsClientStatusChange', (data) => {
|
|
this.broadcast({ success: true, method: 'wsClient.statusChange', result: data });
|
|
});
|
|
app.on('generateCode', (code) => {
|
|
console.log('生成绑定码事件触发,数据:', code);
|
|
if (this.clients.size > 0) {
|
|
console.log("当前连接客户端数量:", this.clients.size);
|
|
this.broadcast({ success: true, method: 'bind.generateCode', result: code.randomCode });
|
|
const refreshDelay = (code.createdAt + (300 - 50) * 1000) - Date.now();
|
|
console.log("下次刷新绑定码时间:", new Date(Date.now() + refreshDelay).toLocaleTimeString());
|
|
if (this.app.CodeTimer) {
|
|
clearTimeout(this.app.CodeTimer);
|
|
}
|
|
this.app.CodeTimer = setTimeout(() => {
|
|
if (this.clients.size > 0) {
|
|
this.app.wsClient.send({ method: 'bind.generateCode', data: {} });
|
|
}
|
|
}, refreshDelay);
|
|
}
|
|
});
|
|
app.on('printerList', (data) => {
|
|
this.broadcast({ success: true, method: 'printer.getWindowsPrinters', result: data });
|
|
});
|
|
}
|
|
_start() {
|
|
this.server = new WebSocketServer({ port: this.port, ...this.options });
|
|
this.server.on('connection', (ws, req) => {
|
|
this.clients.add(ws);
|
|
//console.log('[WSServer] 新客户端连接,当前连接数:', this.clients.size);
|
|
if (typeof this.onConnection === 'function') {
|
|
this.onConnection(ws, req);
|
|
}
|
|
ws.on('message', (msg) => {
|
|
//console.log('[WSServer] 收到消息:', msg);
|
|
this._handleMessage(ws, msg);
|
|
});
|
|
ws.on('close', () => {
|
|
this.clients.delete(ws);
|
|
if (this.clients.size === 0 && this.app.CodeTimer) {
|
|
clearTimeout(this.app.CodeTimer);
|
|
console.log('所有客户端已断开,清除绑定码定时器', this.app.CodeTimer);
|
|
this.app.CodeTimer = null;
|
|
}
|
|
console.log('[WSServer] 客户端断开,当前连接数:', this.clients.size);
|
|
});
|
|
ws.on('error', (err) => {
|
|
this.clients.delete(ws);
|
|
console.log('[WSServer] 客户端错误:', err.message);
|
|
});
|
|
});
|
|
}
|
|
async onConnection(ws, req) {
|
|
const tasks = [];
|
|
|
|
// 发送绑定状态
|
|
if (this.services.setting && typeof this.services.setting.info === 'function') {
|
|
try {
|
|
const info = this.services.setting.info(); // 同步调用
|
|
ws.send(JSON.stringify({ success: true, method: 'setting.info', result: info }));
|
|
} catch (err) {
|
|
ws.send(JSON.stringify({ success: false, message: '获取绑定状态失败: ' + err.message }));
|
|
}
|
|
} else {
|
|
ws.send(JSON.stringify({
|
|
success: false,
|
|
message: 'setting.info 服务不可用',
|
|
debug: {
|
|
availableServices: Object.keys(this.services || {}),
|
|
settingType: typeof this.services?.setting,
|
|
settingKeys: this.services?.setting ? Object.keys(this.services.setting) : []
|
|
}
|
|
}));
|
|
}
|
|
|
|
// 发送打印组件列表
|
|
if (this.services.printerComponent && typeof this.services.printerComponent.getAll === 'function') {
|
|
try {
|
|
const components = this.services.printerComponent.getAll(); // 同步调用
|
|
ws.send(JSON.stringify({ success: true, method: 'printerComponent.getAll', result: components }));
|
|
} catch (err) {
|
|
ws.send(JSON.stringify({ success: false, message: '获取打印组件列表失败: ' + err.message }));
|
|
}
|
|
} else {
|
|
ws.send(JSON.stringify({ success: false, message: 'printerComponent.getAll 服务不可用' }));
|
|
}
|
|
|
|
// 发送打印机列表
|
|
if (this.services.printer && typeof this.services.printer.getWindowsPrinters === 'function') {
|
|
tasks.push(
|
|
this.services.printer.getWindowsPrinters()
|
|
);
|
|
} else {
|
|
ws.send(JSON.stringify({ success: false, message: 'printer.getWindowsPrinters 服务不可用' }));
|
|
}
|
|
|
|
// 发送 WebSocket 客户端状态
|
|
if (this.app.wsClient) {
|
|
ws.send(JSON.stringify({ success: true, method: 'wsClient.statusChange', result: { status: this.app.wsClient.status } }));
|
|
}
|
|
if (!this.app.config.token) {
|
|
//检测是否随机码过期
|
|
if (this.app.randomCode) {
|
|
console.log('当前随机码:', this.app.randomCode);
|
|
console.log('当前时间:', new Date().toLocaleTimeString());
|
|
console.log('随机码过期时间:', new Date(this.app.randomCode.createdAt + this.app.randomCode.expiresIn * 1000).toLocaleTimeString());
|
|
}
|
|
if (this.app.randomCode && this.app.randomCode.createdAt + this.app.randomCode.expiresIn * 1000 > Date.now() && this.app.randomCode.randomCode) {
|
|
this.app.emit('generateCode', this.app.randomCode);
|
|
} else {
|
|
this.app.randomCode = null;
|
|
this.app.wsClient.send({ method: 'bind.generateCode', data: {} });
|
|
}
|
|
}
|
|
// 并行执行所有任务
|
|
await Promise.all(tasks);
|
|
}
|
|
async _handleMessage(ws, msg) {
|
|
// 兼容 Buffer 类型消息
|
|
if (Buffer.isBuffer(msg)) {
|
|
msg = msg.toString('utf8');
|
|
}
|
|
//console.log('[WSServer] 收到消息:', msg);
|
|
let parsed;
|
|
try {
|
|
parsed = typeof msg === 'string' ? JSON.parse(msg) : msg;
|
|
} catch {
|
|
ws.send(JSON.stringify({ success: false, message: '消息解析失败' }));
|
|
return;
|
|
}
|
|
const { method, data } = parsed;
|
|
if (!method) {
|
|
ws.send(JSON.stringify({ success: false, message: 'method不能为空' }));
|
|
return;
|
|
}
|
|
// 支持多级目录结构,如 index.index.index
|
|
const methodPath = method.split('.');
|
|
let serviceFn = this.services;
|
|
for (let i = 0; i < methodPath.length; i++) {
|
|
serviceFn = serviceFn[methodPath[i]];
|
|
if (!serviceFn) break;
|
|
}
|
|
if (typeof serviceFn === 'function') {
|
|
try {
|
|
const result = await serviceFn(data);
|
|
ws.send(JSON.stringify({ success: true, method, result }));
|
|
} catch (err) {
|
|
//console.log(err);
|
|
ws.send(JSON.stringify({ success: false, message: '服务方法执行失败: ' + err.message }));
|
|
}
|
|
} else {
|
|
ws.send(JSON.stringify({
|
|
success: false,
|
|
message: '未找到对应服务方法',
|
|
debug: {
|
|
method,
|
|
methodPath,
|
|
availableServices: Object.keys(this.services || {}),
|
|
topLevelTargetType: typeof this.services?.[methodPath[0]],
|
|
topLevelTargetKeys: this.services?.[methodPath[0]] ? Object.keys(this.services[methodPath[0]]) : []
|
|
}
|
|
}));
|
|
}
|
|
}
|
|
|
|
broadcast(data) {
|
|
const message = typeof data === 'string' ? data : JSON.stringify(data);
|
|
for (const client of this.clients) {
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
client.send(message);
|
|
//console.log('[WSServer] 广播消息:', message);
|
|
}
|
|
}
|
|
}
|
|
|
|
close() {
|
|
if (this.server) {
|
|
this.server.close();
|
|
this.clients.clear();
|
|
//console.log('[WSServer] 服务端关闭');
|
|
}
|
|
}
|
|
}
|
|
|
|
export default WSServer;
|