class WSocket {
ws=null;
timeout=20000;
timeoutObj= null;
serverTimeoutObj=null;
init () {
this.ws = new WebSocket(baseUrl);
this.ws.addEventListener('open', () => {
this.reset().start();
});
this.ws.addEventListener('close', () => {
this.reconnect();
});
this.ws.addEventListener('error', () => {
this.reconnect();
});
this.ws.addEventListener('message', (data) => {
this.ws.reset().start();
store.commit('changeSocketMessage', data);
});
}
reconnect (url) {
setTimeout(function () {
this.init();
}, 2000);
}
reset () {
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
}
start () {
const self = this;
this.timeoutObj = setTimeout(function () {
self.ws.send(JSON.stringify({ type: 3, msg: 'HeartBeat' + new Date() }));
self.serverTimeoutObj = setTimeout(function () {
self.ws.close();
}, self.timeout);
}, self.timeout);
}
}
const $ws = new WSocket();
$ws.init();