webapp: Optimized websocket handling

* auto reconnect
* Url generation
* Disconnect on component change
This commit is contained in:
Thomas Basler 2022-06-18 01:37:47 +02:00
parent 17cc2a475d
commit df45541ae8

View File

@ -78,32 +78,63 @@ export default {
}, },
data() { data() {
return { return {
connection: null, socket: null,
heartInterval: null,
waitForData: true, waitForData: true,
inverterData: [], inverterData: [],
}; };
}, },
created() { created() {
this.initSocket();
},
unmounted() {
this.closeSocket();
},
methods: {
initSocket() {
console.log("Starting connection to WebSocket Server"); console.log("Starting connection to WebSocket Server");
const socketProtocol = const { protocol, host } = location;
window.location.protocol === "https:" ? "wss:" : "ws:"; const webSocketUrl = `${
const port = window.location.port; protocol === "https" ? "wss" : "ws"
const host = window.location.hostname; }://${host}/livedata`;
const webSocketUrl = socketProtocol + "//" + host + ":" + port + "/livedata";
this.connection = new WebSocket(webSocketUrl); this.socket = new WebSocket(webSocketUrl);
this.connection.onmessage = function (event) { this.socket.onmessage = function (event) {
console.log(event); console.log(event);
this.inverterData = JSON.parse(event.data); this.inverterData = JSON.parse(event.data);
this.waitForData = false; this.waitForData = false;
this.heartCheck(); // Reset heartbeat detection
}.bind(this); }.bind(this);
this.connection.onopen = function (event) { this.socket.onopen = function (event) {
console.log(event); console.log(event);
console.log("Successfully connected to the echo websocket server..."); console.log("Successfully connected to the echo websocket server...");
}; };
// Listen to window events , When the window closes , Take the initiative to disconnect websocket Connect
window.onbeforeunload = () => {
this.closeSocket();
};
},
// Send heartbeat packets regularly * 59s Send a heartbeat
heartCheck() {
this.heartInterval && clearTimeout(this.heartInterval);
this.heartInterval = setInterval(() => {
if (this.socket.readyState === 1) {
// Connection status
this.socket.send("ping");
} else {
this.initSocket(); // Breakpoint reconnection 5 Time
}
}, 59 * 1000);
},
/** To break off websocket Connect */
closeSocket() {
this.socket.close();
this.heartInterval && clearTimeout(this.heartInterval);
},
}, },
}; };
</script> </script>