Skip to content

Instantly share code, notes, and snippets.

@msh9
Last active August 3, 2016 13:39
Show Gist options
  • Save msh9/56d5d551680488e3f3c4283d50ab5aa9 to your computer and use it in GitHub Desktop.
Save msh9/56d5d551680488e3f3c4283d50ab5aa9 to your computer and use it in GitHub Desktop.
Handling WebSocket Errors
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>WebSocket Demostration</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p>Hello world!</p>
<script>
var socket
function sendMessage(socket) {
socket.send('Boo!');
console.log('Sent boo!');
setTimeout(function () { sendMessage(socket); }, 60000);
}
function sendUnidirectionHeartbeat(socket) {
socket.send('tale tell heart');
}
function setupSocket() {
socket = new WebSocket("ws://localhost:8080");
socket.onopen = function (event) {
sendMessage(socket);
setInterval(function () { sendUnidirectionHeartbeat(socket) }, 30000);
sendUnidirectionalHeartbeat(socket);
}
socket.onmessage = function (message) {
console.log('Got message: ' + message);
}
socket.onclose = function (event) {
console.log('Connection closing--reopening now');
setupSocket();
}
socket.onerror = function (event) {
console.log('Error occured, closing and reopening');
socket.close();
}
}
setupSocket();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment