Last active
December 6, 2018 03:21
-
-
Save xemasiv/138488648d447689dde5d7826bd1c64e to your computer and use it in GitHub Desktop.
Reconnecting Websockets
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
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