191 lines
7.3 KiB
JavaScript
191 lines
7.3 KiB
JavaScript
import WebSocket from 'ws';
|
||
import path from 'path';
|
||
import fs from 'fs';
|
||
|
||
class WSClient {
|
||
constructor(url, options = {}, app) {
|
||
this.url = url;
|
||
this.options = options;
|
||
this.ws = null;
|
||
this.status = 'disconnected';
|
||
//console.log('[WSClient] app', app);
|
||
this.services = app.services || {};
|
||
this.heartbeatTimerInterval = 10000; // 心跳间隔,默认10秒
|
||
this.app = app;
|
||
this.reconnectInterval = options.reconnectInterval || 3000; // 重连间隔,默认3秒
|
||
this._reconnectTimer = null;
|
||
//console.log('[WSClient] 初始化,目标地址:', this.url);
|
||
this._connect();
|
||
app.on('printerComponentStatusChange', (data) => {
|
||
if (this.app.info) {
|
||
console.log("组件状态变化,通知远程服务器", data);
|
||
this.send({ method: 'printerComponent.statusChange', data });
|
||
}
|
||
});
|
||
app.on("printResult", (data) => {
|
||
if (this.app.info) {
|
||
console.log("打印结果,通知远程服务器", data);
|
||
this.send({ method: 'base.printResult', data });
|
||
}
|
||
});
|
||
//获取打印机列表事件通知远程服务器
|
||
app.on("printerList", (data) => {
|
||
if (this.app.info) {
|
||
//console.log("打印机列表,通知远程服务器", data);
|
||
this.send({ method: 'base.printerList', data });
|
||
}
|
||
});
|
||
}
|
||
|
||
_connect() {
|
||
if (this.ws) {
|
||
try {
|
||
this.ws.terminate();
|
||
} catch (e) {
|
||
//console.log('[WSClient] 关闭旧连接异常:', e.message);
|
||
}
|
||
this.ws = null;
|
||
}
|
||
if (this._reconnectTimer) {
|
||
clearTimeout(this._reconnectTimer);
|
||
this._reconnectTimer = null;
|
||
}
|
||
//console.log('[WSClient] 尝试连接:', this.url);
|
||
this.ws = new WebSocket(this.url, this.options);
|
||
this.ws.on('open', () => {
|
||
this.status = 'connected';
|
||
this._handleOpen();
|
||
this.app.emit('wsClientStatusChange', { status: 'connected', url: this.url });
|
||
});
|
||
this.ws.on('message', (msg) => {
|
||
if (Buffer.isBuffer(msg)) {
|
||
msg = msg.toString('utf8');
|
||
}
|
||
console.log('[WSClient] 收到消息:', msg);
|
||
this._handleMessage(msg);
|
||
});
|
||
this.ws.on('close', () => {
|
||
this.status = 'disconnected';
|
||
//console.log('[WSClient] 连接关闭,准备重连');
|
||
this.app.emit('wsClientStatusChange', { status: 'disconnected', url: this.url });
|
||
if (this.onClose) this.onClose();
|
||
this._reconnect();
|
||
});
|
||
this.ws.on('error', (err) => {
|
||
this.status = 'error';
|
||
//console.log('[WSClient] 连接错误:', err.message);
|
||
this.app.emit('wsClientStatusChange', { status: 'error', url: this.url, error: err.message });
|
||
this._reconnect();
|
||
});
|
||
}
|
||
|
||
_reconnect() {
|
||
//清理现有连接和定时器
|
||
this.app.randomCode = null; // 清除随机码
|
||
this.app.info = null; // 清除用户信息
|
||
if (this.status === 'connected' || this._reconnectTimer) return;
|
||
//console.log(`[WSClient] ${this.reconnectInterval}ms 后重试连接...`);
|
||
this._reconnectTimer = setTimeout(() => {
|
||
this._connect();
|
||
}, this.reconnectInterval);
|
||
}
|
||
async _handleOpen() {
|
||
/*console.log('[WSClient] _handleOpen 调试:', {
|
||
status: this.status,
|
||
url: this.url,
|
||
config: this.app.config
|
||
});*/
|
||
//设置心跳
|
||
const { token } = this.app.config;
|
||
this.send({ method: 'auth.getInfo', data: token });
|
||
this.startHeartbeat();
|
||
}
|
||
async startHeartbeat() {
|
||
if (this.heartbeatTimer) {
|
||
clearInterval(this.heartbeatTimer);
|
||
}
|
||
this.heartbeatTimer = setInterval(() => {
|
||
if (this.status === 'connected') {
|
||
this.send('ping');
|
||
const { token, refreshToken, tokenExpireTime } = this.app.config;
|
||
console.log(this.app.info,"this.app.info的值")
|
||
if (!this.app.info && token && refreshToken && tokenExpireTime) {
|
||
if (tokenExpireTime < Date.now()) {
|
||
//console.log('[WSClient] 心跳检测: token 已过期,尝试刷新');
|
||
this.send({ method: 'auth.refreshToken', data: { token: refreshToken } });
|
||
} else {
|
||
//拉取信息
|
||
this.send({ method: 'auth.getInfo', data: token });
|
||
}
|
||
}
|
||
}
|
||
}, this.heartbeatTimerInterval);
|
||
}
|
||
async _handleMessage(msg) {
|
||
if(msg === 'pong') {
|
||
//console.log('[WSClient] 收到心跳响应');
|
||
return;
|
||
}
|
||
//console.log("[WSClient]原始消息", msg)
|
||
let parsed;
|
||
try {
|
||
parsed = typeof msg === 'string' ? JSON.parse(msg) : msg;
|
||
} catch {
|
||
//console.log('[WSClient] 消息解析失败:', msg);
|
||
this.send({ success: false, message: '消息解析失败' });
|
||
return;
|
||
}
|
||
const { method, data } = parsed;
|
||
//console.log('[WSClient] 可用服务列表:', method, this.services, '方法:', method);
|
||
if (!method) {
|
||
//this.send({ success: false, message: '消息缺少 method 字段' });
|
||
return;
|
||
}
|
||
const methodPath = method.split('.');
|
||
let serviceFn = this.services;
|
||
for (let i = 0; i < methodPath.length; i++) {
|
||
serviceFn = serviceFn[methodPath[i]];
|
||
//console.log("serviceFn", serviceFn,methodPath[i]);
|
||
if (!serviceFn) break;
|
||
}
|
||
if (typeof serviceFn === 'function') {
|
||
try {
|
||
const result = await serviceFn(data);
|
||
if (result !== undefined) {
|
||
const responseMethod = result && typeof result === 'object' && result.method
|
||
? result.method
|
||
: method;
|
||
this.ws.send(JSON.stringify({ success: true, method: responseMethod, result }));
|
||
}
|
||
} catch (err) {
|
||
//console.log(`[WSClient] 服务方法执行失败: ${method}`, err);
|
||
//this.ws.send(JSON.stringify({ success: false, message: '服务方法执行失败: ' + err.message }));
|
||
}
|
||
} else {
|
||
//console.log(`[WSClient] 未找到对应服务方法: ${method}`);
|
||
//this.ws.send(JSON.stringify({ success: false, message: '未找到对应服务方法' }));
|
||
}
|
||
}
|
||
|
||
send(data) {
|
||
if (this.status === 'connected') {
|
||
//console.log('[WSClient] 发送消息:', data);
|
||
this.ws.send(typeof data === 'string' ? data : JSON.stringify(data));
|
||
}
|
||
}
|
||
|
||
close() {
|
||
if (this.ws) {
|
||
//console.log('[WSClient] 主动关闭连接');
|
||
this.ws.terminate();
|
||
this.ws = null;
|
||
}
|
||
if (this._reconnectTimer) {
|
||
clearTimeout(this._reconnectTimer);
|
||
this._reconnectTimer = null;
|
||
}
|
||
}
|
||
}
|
||
|
||
export default WSClient;
|