Skip to content

Instantly share code, notes, and snippets.

@xemasiv
Last active December 6, 2018 03:21
Show Gist options
  • Save xemasiv/138488648d447689dde5d7826bd1c64e to your computer and use it in GitHub Desktop.
Save xemasiv/138488648d447689dde5d7826bd1c64e to your computer and use it in GitHub Desktop.
Reconnecting Websockets
var socket;
const socketMessageListener = (event) => {
console.log(event.data);
};
const socketOpenListener = (event) => {
console.log('Connected');
socket.send('hello');
};
const socketCloseListener = (event) => {
if (socket) {
console.error('Disconnected.');
}
socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', socketOpenListener);
socket.addEventListener('message', socketMessageListener);
socket.addEventListener('close', socketCloseListener);
};
socketCloseListener();
// For testing:
// We disconnect it 5 seconds after running.
// It will flawlessly reconnect.
setTimeout(()=>{
socket.close();
},5000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment