Skip to content

Instantly share code, notes, and snippets.

@tusqasi
Last active August 31, 2023 18:09
Show Gist options
  • Save tusqasi/ca644dff0f9c12530ab1e7ccbe56320d to your computer and use it in GitHub Desktop.
Save tusqasi/ca644dff0f9c12530ab1e7ccbe56320d to your computer and use it in GitHub Desktop.
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");
@tusqasi
Copy link
Author

tusqasi commented Jan 8, 2023

A simple function to connect to a web socket server at URL. Good enough to get started as boilerplate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment