Refactor JS, handle WebSocket errors
This commit is contained in:
parent
0b65c79a89
commit
952b8940c9
|
@ -95,26 +95,52 @@
|
|||
var queue = [];
|
||||
var archive = [];
|
||||
|
||||
// Construct websocket url
|
||||
var loc = window.location;
|
||||
var ws_url = ((loc.protocol === "https:") ? "wss://" : "ws://") + loc.host + "/ws";
|
||||
function connectWebSocket(url) {
|
||||
var webSocket = new WebSocket(url);
|
||||
|
||||
var exampleSocket = new WebSocket(ws_url);
|
||||
exampleSocket.onopen = function (event) {
|
||||
console.log("WS: Connection open");
|
||||
};
|
||||
exampleSocket.onmessage = function (event) {
|
||||
console.log("WS: Received message");
|
||||
IT = JSON.parse(event.data);
|
||||
if (IT["State"] === 1) {
|
||||
queue.push(IT);
|
||||
archive.push(IT);
|
||||
webSocket.onopen = function(event) {
|
||||
console.log("WebSocket: Connected");
|
||||
}
|
||||
|
||||
webSocket.onmessage = function(event) {
|
||||
console.log("WebSocket: Received Message");
|
||||
handleMessage(event.data);
|
||||
}
|
||||
|
||||
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) {
|
||||
archive.shift();
|
||||
}
|
||||
}
|
||||
console.log(event.data);
|
||||
}
|
||||
|
||||
function displayNewSnap() {
|
||||
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();
|
||||
connectWebSocket(ws_url);
|
||||
</script>
|
||||
|
||||
</body>
|
||||
|
|
Loading…
Reference in a new issue