Skip to content

Instantly share code, notes, and snippets.

@pladaria
Last active June 27, 2016 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pladaria/d63ab72243f99c59e805f0ab5f74e1b7 to your computer and use it in GitHub Desktop.
Save pladaria/d63ab72243f99c59e805f0ab5f74e1b7 to your computer and use it in GitHub Desktop.
Quick and dirty draft of a reconnecting websocket with connecting timeout
/**
* 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()
@pladaria
Copy link
Author

pladaria commented Jun 27, 2016

Simple ws echo server for testing previous code

  • Requires ws: npm install ws
  • Send crash to crash the server
  • Send hang to hang the server
const WebSocketServer = require('ws').Server
const wss = new WebSocketServer({port: 8080})
wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    console.log('received: %s', message)
    if (message === 'crash') {
        throw Error('crash')
    }
    if (message === 'hang') {
        while (true) {}
    }
    ws.send(message)
  })
  ws.send('hello')
})

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