From 4453f2dc51a03500829b30621033516addcadb06 Mon Sep 17 00:00:00 2001 From: elijahr2411 Date: Fri, 27 Jan 2023 23:52:25 -0500 Subject: [PATCH] auto reconnect on connection close --- src/index.js | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/src/index.js b/src/index.js index 3eea230..e19b0c1 100644 --- a/src/index.js +++ b/src/index.js @@ -65,12 +65,28 @@ class CollabVMClient { } connect() { return new Promise((res, rej) => { - this.socket = new WebSocket(this.#url, "guacamole"); + try { + this.socket = new WebSocket(this.#url, "guacamole"); + } catch (e) { + rej(e); + } this.socket.addEventListener('message', (e) => this.#onMessage(e)); this.socket.addEventListener('open', () => res(), {once: true}); }) } + #onClose() { + cleanup(); + setTimeout(async () => { + try { + await this.connect(); + } catch { + console.log("h"); + this.#onClose(); + } + this.connectToVM(this.node); + }, 2000); + } disconnect() { this.socket.send(guacutils.encode(["disconnect"])); this.socket.close(); @@ -80,6 +96,7 @@ class CollabVMClient { } connectToVM(node) { return new Promise((res, rej) => { + this.socket.addEventListener('close', () => this.#onClose()); this.node = node; var savedUsername = window.localStorage.getItem("username"); if (savedUsername === null) @@ -643,6 +660,23 @@ function screenshotVM() { }, "image/png"); }) } +// Clean everything up after disconnecting +function cleanup() { + turn = -1; + window.username = null; + rank = 0; + hasTurn = false; + if (turninterval) clearInterval(turninterval); + if (voteinterval) + clearInterval(voteinterval); + users.splice(0); + userlist.innerHTML = ""; + Array.prototype.slice.call(staffbtns.children).forEach((curr) => curr.style.display = "none"); + staffbtns.style.display = "none"; + usernameSpan.classList = "input-group-text bg-dark text-light"; + display.height = 0; + display.width = 0; +} buttons.screenshot.addEventListener('click', async () => { var blob = await screenshotVM(); var url = URL.createObjectURL(blob);