Refactor JS, handle WebSocket errors

This commit is contained in:
Marvin Scholz 2017-05-13 02:34:15 +02:00
parent 0b65c79a89
commit 952b8940c9

View file

@ -95,26 +95,52 @@
var queue = []; var queue = [];
var archive = []; var archive = [];
// Construct websocket url function connectWebSocket(url) {
var loc = window.location; var webSocket = new WebSocket(url);
var ws_url = ((loc.protocol === "https:") ? "wss://" : "ws://") + loc.host + "/ws";
var exampleSocket = new WebSocket(ws_url); webSocket.onopen = function(event) {
exampleSocket.onopen = function (event) { console.log("WebSocket: Connected");
console.log("WS: Connection open"); }
};
exampleSocket.onmessage = function (event) { webSocket.onmessage = function(event) {
console.log("WS: Received message"); console.log("WebSocket: Received Message");
IT = JSON.parse(event.data); handleMessage(event.data);
if (IT["State"] === 1) { }
queue.push(IT);
archive.push(IT); webSocket.onclose = function(event) {
console.log("WebSocket: Closed");
setTimeout(function() {
connectWebSocket(url);
}, 5000);
}
webSocket.onerror = function(event) {
console.warn("WebSocket: Error, closing socket");
ws.close();
}
}
function handleMessage(message) {
var item = null;
try {
item = JSON.parse(message);
} catch (err) {
console.warn("MessageHandler: Failed Message JSON parsing");
return;
}
if (item["State"] === 1) {
addItem(item);
}
}
function addItem(item) {
queue.push(item);
archive.push(item);
if (archive.length > 5) { if (archive.length > 5) {
archive.shift(); archive.shift();
} }
} }
console.log(event.data);
}
function displayNewSnap() { function displayNewSnap() {
var item = queue.shift(); var item = queue.shift();
@ -180,7 +206,12 @@ function setDisplayItem(item) {
} }
} }
// Construct websocket url
var loc = window.location;
var ws_url = ((loc.protocol === "https:") ? "wss://" : "ws://") + loc.host + "/ws";
loadInitialSnaplist(); loadInitialSnaplist();
connectWebSocket(ws_url);
</script> </script>
</body> </body>