From d9501602ece10fc4cc75390928ed208919f700b0 Mon Sep 17 00:00:00 2001 From: Elijah R Date: Mon, 18 Dec 2023 16:50:57 -0500 Subject: [PATCH] cleanly handle socket closure --- src/VM.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/VM.ts b/src/VM.ts index 870c292..00d521b 100644 --- a/src/VM.ts +++ b/src/VM.ts @@ -13,6 +13,7 @@ export default class VM { #writeLock : Mutex = new Mutex(); #messageQueue : Queue = new Queue(); #nopTimeout : NodeJS.Timeout | null = null; + #reconnectTimeout : NodeJS.Timeout | null = null; isConnectedToVM : boolean = false; #noNop : boolean = false; connected : boolean = false; @@ -29,11 +30,24 @@ export default class VM { this.#socket.connect(socketpath); this.#socket.on('connect', () => { this.connected = true; - log("INFO", `Connected to VM at ${socketpath}`); + log("INFO", `Connected to ${id} at ${socketpath}`); this.#enqueueMessage({ Operation: protocol.ProtocolOperation.NOP }); }); + this.#socket.on('close', () => { + this.connected = false; + log("INFO", `Disconnected from ${id} at ${socketpath}`); + log("INFO", "Reconnecting in 5 seconds..."); + this.#reconnectTimeout = setTimeout(() => { + this.#reconnectTimeout = null; + this.#socket.connect(socketpath); + }, 5000); + }); + this.#socket.on('error', (err) => { + log("ERROR", `Error on socket ${id} at ${socketpath}: ${err.message}`); + + }); this.#socket.on('data', (data) => this.#onData(data)); this.#events = new EventEmitter(); this.#events.on('ack', () => {