Last active
June 27, 2016 17:47
-
-
Save pladaria/d63ab72243f99c59e805f0ab5f74e1b7 to your computer and use it in GitHub Desktop.
Quick and dirty draft of a reconnecting websocket with connecting timeout
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
/** | |
* Quick and dirty draft of a reconnecting websocket with connecting timeout | |
*/ | |
console.debug('script init') | |
const MAX_RECONNECTION_DELAY = 8000 | |
const MIN_RECONNECTION_DELAY = 1500 | |
const CONNECTING_TIMEOUT = 5000 | |
const RECONNECTION_DELAY_MULTIPLIER = 1.3 | |
let reconnectDelay = 0 | |
let ws | |
const initReconnectDelay = () => { | |
reconnectDelay = MIN_RECONNECTION_DELAY + Math.random() * MIN_RECONNECTION_DELAY | |
console.debug('init reconnect delay:', reconnectDelay) | |
} | |
const updateReconnectionDelay = () => { | |
reconnectDelay *= RECONNECTION_DELAY_MULTIPLIER | |
if (reconnectDelay > MAX_RECONNECTION_DELAY) { | |
reconnectDelay = MAX_RECONNECTION_DELAY | |
} | |
console.debug('update reconnect delay:', reconnectDelay) | |
} | |
const connect = () => { | |
ws = new WebSocket('ws://localhost:8080') | |
const connectingTimeout = setTimeout(() => { | |
console.debug('connecting timeout:', CONNECTING_TIMEOUT) | |
ws.close() | |
}, CONNECTING_TIMEOUT) | |
ws.onmessage = (ev) => console.debug('>', ev.data) | |
ws.onclose = (ev) => { | |
console.debug('close:', ev) | |
if (!reconnectDelay) { | |
initReconnectDelay() | |
} else { | |
updateReconnectionDelay() | |
} | |
setTimeout(connect, reconnectDelay) | |
} | |
ws.onerror = (ev) => console.debug('error:', ev) | |
ws.onopen = (ev) => { | |
initReconnectDelay() | |
clearTimeout(connectingTimeout) | |
console.debug('open:', ev) | |
} | |
} | |
connect() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple ws echo server for testing previous code
npm install ws
crash
to crash the serverhang
to hang the server