最後に、次のように vue+ts で ws auto reconnect を作成します。
private async mounted() {
// Connect to WebSocket
const sn = "sb1234567890";
const host =
window.location.protocol == "https:"
? "wss://www.xxx.net"
: process.env.DEV_TYPE === "fullstack"
? "ws://10.0.0.14:8528"
: "ws://www.xxx.net:8528";
const wsUri = host + "/feed-home/" + sn;
await this.startWs(wsUri, sn);
// !!!Deprecated: failed to reconnect
// let ws = new WebSocket();
// console.log(ws);
// ws.onopen = async function(event) {
// console.log(event, "openEvent");
// clearInterval(that.timer);
// };
// ws.onclose = async function(event) {
// console.log(event, "close");
// that.timer = setInterval(() => {
// console.log("Heart Beat");
// ws.send("HeartBeat");
// // ws = new WebSocket("ws://10.0.0.14:8528/feed-home/" + sn);
// console.log(ws);
// }, 60000);
// };
// ws.onmessage = async function(event) {
// console.log(event, "ws");
// alert("get it!");
// await alert("please update!");
// await that.getHome(sn);
// };
}
private wsReconnected: boolean = false; // check whether WebSocket is reconnected
private async startWs(uri: string, sn: string) {
let that = this;
let ws = new WebSocket(uri);
ws.onopen = async () => {
if (that.wsReconnected) {
await that.getHome(sn); // Refresh api data after reconnected
}
ws.send("Current client version: " + window.version);
};
ws.onmessage = async evt => {
await that.getHome(sn);
that.$message({
type: "success",
message: evt.data,
showClose: true,
center: true,
duration: 20 * 1000
});
};
ws.onclose = async () => {
that.wsReconnected = true;
await that.startWs(uri, sn);
const sleep = (seconds: number) => {
return new Promise(resolve =>
setTimeout(resolve, seconds * 1000)
);
};
await sleep(10); // Try to reconnect in 10 seconds
// !!!Deprecated: Use timer will cause multiply ws connections
// if (!that.wsTimer) {
// // Try to reconnect in 10 seconds
// that.wsTimer = setInterval(async () => {
// console.log("reconnecting websocket...");
// await that.startWs(uri, sn);
// }, 10 * 1000);
// }
};
}