Skip to content

Instantly share code, notes, and snippets.

@kuczmama
Created January 23, 2020 00:14
Show Gist options
  • Save kuczmama/f16ad44819fdb2e1699dc96a99883f5e to your computer and use it in GitHub Desktop.
Save kuczmama/f16ad44819fdb2e1699dc96a99883f5e to your computer and use it in GitHub Desktop.
function connect() {
const URL = 'wss://localhost:8080';
const RECONNECT_DELAY = 1000;
const WAIT_FOR_NO_MESSAGE = 30000;
const handler = null;
var ws = new WebSocket(URL);
ws.onmessage = function(e) {
clearTimeout(handler);
setTimeout(() => ws.close(), WAIT_FOR_NO_MESSAGE);
console.log('Message:', e.data);
};
ws.onclose = function(e) {
console.log(`Socket is closed. Reconnect will be attempted in ${RECONNECT_DELAY / 1000 | 0} second.`, e.reason);
ws = null;
setTimeout(function() {
connect();
}, RECONNECT_DELAY);
};
ws.onerror = function(err) {
console.error('Socket encountered error: ', err.message, 'Closing socket');
ws.close();
};
}
connect();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment