cleanly handle socket closure

This commit is contained in:
Elijah R 2023-12-18 16:50:57 -05:00
parent dc1fe1600f
commit d9501602ec

View file

@ -13,6 +13,7 @@ export default class VM {
#writeLock : Mutex = new Mutex(); #writeLock : Mutex = new Mutex();
#messageQueue : Queue<protocol.ProtocolMessage> = new Queue<protocol.ProtocolMessage>(); #messageQueue : Queue<protocol.ProtocolMessage> = new Queue<protocol.ProtocolMessage>();
#nopTimeout : NodeJS.Timeout | null = null; #nopTimeout : NodeJS.Timeout | null = null;
#reconnectTimeout : NodeJS.Timeout | null = null;
isConnectedToVM : boolean = false; isConnectedToVM : boolean = false;
#noNop : boolean = false; #noNop : boolean = false;
connected : boolean = false; connected : boolean = false;
@ -29,11 +30,24 @@ export default class VM {
this.#socket.connect(socketpath); this.#socket.connect(socketpath);
this.#socket.on('connect', () => { this.#socket.on('connect', () => {
this.connected = true; this.connected = true;
log("INFO", `Connected to VM at ${socketpath}`); log("INFO", `Connected to ${id} at ${socketpath}`);
this.#enqueueMessage({ this.#enqueueMessage({
Operation: protocol.ProtocolOperation.NOP 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.#socket.on('data', (data) => this.#onData(data));
this.#events = new EventEmitter(); this.#events = new EventEmitter();
this.#events.on('ack', () => { this.#events.on('ack', () => {