class Socket { constructor(path) { const url = this.url = new Url(); if(url.getProtocol() === 'https:') url.setProtocol('wss'); else url.setProtocol('ws'); url.setPath(path).setHash(); try { this.connection = new WebSocket(url.toString()); this.keepAlive = setInterval(() => { this.connection.send('keep-alive'); }, 20000); this.connection.onclose = (e) => { clearInterval(this.keepAlive); }; } catch(e) { this.connection = null; } } onOpen(onopen) { if(this.connection) this.connection.onopen = onopen; return this; } onMessage(onmessage) { if(this.connection) this.connection.onmessage = onmessage; return this; } onError(onerror) { if(this.connection) this.connection.onerror = onerror; return this; } onClose(onclose) { if(this.connection) this.connection.onclose = (e) => { clearInterval(this.keepAlive); onclose(e); }; return this; } }