Create a gist now

Instantly share code, notes, and snippets.

@msh9 /index.html
Last active Aug 3, 2016

What would you like to do?
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