netkitty
Version:
Network tools kit
60 lines (59 loc) • 2.19 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PipeServer = void 0;
const GeneratePipeAddress_1 = require("../GeneratePipeAddress");
const events_1 = __importDefault(require("events"));
const socket_ipc_1 = require("socket-ipc");
const PipeClientSocket_1 = require("./PipeClientSocket");
class PipeServer extends events_1.default {
#server;
#clientSocketMap;
get clients() {
return this.#clientSocketMap;
}
constructor(options) {
super();
this.#clientSocketMap = new Map();
this.actions = {};
this.actions = options?.actions ? options.actions : {};
this.socketPath = (0, GeneratePipeAddress_1.GeneratePipeAddress)();
this.#server = new socket_ipc_1.MessageServer({ path: this.socketPath });
this.#server.on('connection', (connection) => {
connection.once('message', (message) => {
const base64Id = message.data.toString();
const clientId = Buffer.from(base64Id, 'base64').toString();
const clientSocket = new PipeClientSocket_1.PipeClientSocket({
id: clientId,
connection: connection,
actions: this.actions
});
this.#clientSocketMap.set(clientId, clientSocket);
clientSocket.once('disconnect', () => {
this.#clientSocketMap.delete(clientSocket.id);
this.emit('disconnect', clientSocket);
});
this.emit('connect', clientSocket);
});
});
this.#server.start().then(() => this.emit('ready'));
}
/**
* Dispose pipe server
*/
dispose() {
this.#server.stop();
this.#clientSocketMap.clear();
}
on(eventName, listener) {
super.on(eventName, listener);
return this;
}
once(eventName, listener) {
super.once(eventName, listener);
return this;
}
}
exports.PipeServer = PipeServer;