slate/node_common/nodejs-websocket.js

51 lines
1.1 KiB
JavaScript
Raw Normal View History

import * as Environment from "~/node_common/environment";
import * as Strings from "~/common/strings";
import * as Logging from "~/common/logging";
import WebSocket from "ws";
let ws;
export const create = () => {
if (ws) {
return;
}
if (Strings.isEmpty(Environment.URI_FIJI)) {
return;
}
ws = new WebSocket(Environment.URI_FIJI, {
perMessageDeflate: false,
});
2021-01-10 01:34:50 +03:00
ws.on("ping", function () {
clearTimeout(this.pingTimeout);
this.pingTimeout = setTimeout(() => {
Logging.log(`Did not receive ping in time. Disconnecting websocket`);
this.terminate();
}, 30000 + 1000);
});
ws.on("open", () => {
ws.send(JSON.stringify({ type: "SUBSCRIBE_HOST", data: {} }));
});
ws.on("close", () => {
2021-01-10 04:58:36 +03:00
global.websocket = null;
setTimeout(() => {
Logging.log(`Auto reconnecting websocket`);
2021-01-10 04:58:36 +03:00
create();
}, 1000);
Logging.log(`Websocket disconnected`);
});
Logging.log(`Websocket server started`);
global.websocket = ws;
return global.websocket;
};
export const get = () => global.websocket;