Last active
August 31, 2023 18:09
-
-
Save tusqasi/ca644dff0f9c12530ab1e7ccbe56320d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let reconnects = 0; | |
let socket; | |
function connectWebsocket(url) { | |
socket = new WebSocket(url); | |
socket.onmessage = function onmessage_callback(message) { | |
// recieve messages here | |
}; | |
socket.onopen = function onopen_callback() { | |
console.log("Connected to: " + socket.url); | |
socket.send(JSON.stringify({"Hi":"from client"})); | |
}; | |
socket.onclose = function onclose_callback(event) { | |
console.error("Connection Closed: "); | |
reconnects++; | |
if (reconnects > 10) { | |
console.error("Tried reconnecting {reconnect} times"); | |
} else { | |
console.warn("Trying to reconnect"); | |
setTimeout(function () { | |
connectWebsocket(url); | |
}, 5000); | |
} | |
}; | |
socket.onerror = function onerror_callback(_) { | |
console.warn("Error Occured. Trying to reconnect."); | |
setTimeout(function () { | |
connectWebsocket(url); | |
}, 5000); | |
}; | |
} | |
connectWebsocket("change url here"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A simple function to connect to a web socket server at URL. Good enough to get started as boilerplate.