qe-cli
Version:
qe-cli
103 lines (102 loc) • 3.73 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ws_client = void 0;
const events_1 = require("events");
const WebSocket = require("ws");
const ps_1 = require("./ps");
class ws_client extends events_1.EventEmitter {
constructor(config) {
super();
this.config = config;
if (!this.config.timeout || this.config.timeout < 1) {
this.config.timeout = 5000;
}
}
async connect() {
let tick_time = process.uptime();
this.client = new WebSocket((this.config.url?.endsWith("/") ? this.config.url : this.config.url + "/"));
this.client.on('open', async () => {
if (this.config.debug) {
console.log("ws:open");
}
this.emit("connect", "");
while (true && this.client?.readyState == WebSocket.OPEN) {
if (process.uptime() - tick_time > this.config.timeout) {
if (this.config.debug) {
console.log("ws:tick timeout");
}
this.client.close();
break;
}
if (this.client?.readyState == WebSocket.OPEN) {
this.client.send(Buffer.alloc(1));
}
await ps_1.ps.sleep(1000);
}
});
this.client.on('ping', () => {
if (this.config.debug) {
console.log("ws:ping");
}
tick_time = process.uptime();
});
this.client.on('error', (err) => {
if (this.config.debug) {
console.log("ws:error");
console.log(err);
}
});
this.client.on('message', (msg, isBinary) => {
tick_time = process.uptime();
if (isBinary) {
if (this.config.debug) {
console.log("ws:tick");
}
return;
}
if (this.config.debug) {
console.log("ws:message");
}
try {
let json = JSON.parse(msg.toString());
if (json?.code === 1) {
if (json.data.cmd.callback) {
let cb = async (result) => {
this.client.send(JSON.stringify({
callback: json.data.cmd.callback,
result: result
}));
};
this.emit("onmessage", json.data.cmd.event, json.data.cmd.args, cb);
}
else {
this.emit("onmessage", json.data.cmd.event, json.data.cmd.args);
}
}
}
catch (e) {
console.error("parseData error:" + e.toString(), msg.toString(), msg);
}
});
this.client.on('close', async () => {
if (this.config.debug) {
console.log("ws:close");
}
this.client.removeAllListeners();
this.emit("disconnect", "");
await ps_1.ps.sleep(1100);
setTimeout(() => {
if (this.config.debug) {
console.log("reconnect");
}
this.connect();
}, this.config.timeout);
});
}
async send(json) {
if (this.client?.readyState == WebSocket.OPEN) {
await this.client.send(JSON.stringify(json));
}
}
}
exports.ws_client = ws_client;