From c0af840b42cf4875e342414e256e345fcb11b3a2 Mon Sep 17 00:00:00 2001 From: Kubat <mael.martin31@gmail.com> Date: Mon, 5 Oct 2020 10:17:33 +0200 Subject: [PATCH] A working socket --- common/lkt.js | 71 ++++++++++++++++++++++++++++++++++++++++++++++++ test/test_lkt.js | 6 ++++ 2 files changed, 77 insertions(+) create mode 100644 test/test_lkt.js diff --git a/common/lkt.js b/common/lkt.js index e69de29..662b918 100644 --- a/common/lkt.js +++ b/common/lkt.js @@ -0,0 +1,71 @@ +const logger = require.main.require('./common/logger.js'); +const net = require('net'); + +class LktClient { + + /* The constructor + * - host: String + * - port: String + * + * Private members + * - m_socket: net.socket */ + constructor(port = 6600) { + this.m_online = false; + this.m_port = port; + this.m_socket = new net.Socket(); + const sockopt = { + port: this.m_port, + host: "localhost", + readable: true, + writable: true + }; + + logger.log("debug", "Creating the lektor client"); + this.m_socket.setTimeout(10); + this.m_socket.setEncoding('utf8'); + this.m_socket.on("timeout", () => { + logger.log("error", `Got timeout while connecting to localhost:${this.m_port}`); + this.m_socket.end(); + }); + + this.m_socket.on("ready", () => { + logger.log("debug", `Ready to use socker with localhost:${this.m_port}`); + this.m_online = true; + }); + + this.m_socket.on('data', (data) => { + logger.log("debug", `Recieved "${data.replace(/(\r\n|\n|\r)/gm, "")}"`); + }); + + this.m_socket.on("end", () => { + logger.log("info", `Disconnected from server localhost:${this.m_port}`); + this.m_online = false; + }); + + this.m_socket.on("close", () => { + logger.log("info", `Socket localhost:${this.m_port} closed`); + this.m_online = false; + }); + + this.m_socket.connect(sockopt, () => { + logger.log("info", `Socket connected to localhost:${this.m_port}`); + this.m_online = true; + }); + } + + /* Wait for the socket to be connected */ + wait() { + logger.log("debug", `Waiting to connect to localhost:${this.m_port}`); + var i = 0; + while (! this.m_online) { + } + } + + /* Close the client */ + close() { + logger.log("debug", "Requesting socket shutdown"); + this.m_socket.destroy(); + } +} + +module.exports = LktClient; diff --git a/test/test_lkt.js b/test/test_lkt.js new file mode 100644 index 0000000..54b3dc0 --- /dev/null +++ b/test/test_lkt.js @@ -0,0 +1,6 @@ +const logger = require.main.require('./common/logger.js'); +const lkt = require.main.require('./common/lkt.js'); + +var client = new lkt(); + +// client.wait(); -- GitLab