const WEBSOCKET = function (model) { let wsUrl = ['localhost', 'silvrtree.co.uk']; let wsPort = '9000'; const useUrl = 0; if ('https:' === document.location.protocol) { wsUrl = `wss://${ wsUrl[useUrl] }`; wsPort = ''; } else { // wsUrl = 'ws://localhost:3001'; wsUrl = `ws://${ wsUrl[useUrl] }`; wsPort = '9000'; } console.log('>> wsUrl', wsUrl); this.socket = null; this.timer = 0; this.clock = null; this.startWebSocket = function () { 'use strict'; const url = (wsPort === '') ? wsUrl : `${wsUrl }:${ wsPort}`; console.log('Starting socket', url); const wsCtor = window['MozWebSocket'] ? MozWebSocket : WebSocket; this.socket = new wsCtor(url, 'stream'); this.socket.onopen = this.handleWebsocketOnOpen.bind(this); this.socket.onmessage = this.handleWebsocketMessage.bind(this); this.socket.onclose = this.handleWebsocketClose.bind(this); this.socket.onerror = function (e) { console.error(e); }; }; this.send = function (msg) { console.log('Sending', msg); this.socket.send(msg); }; this.handleData = function (d) { model.trigger('message', d); }; this.handleWebsocketOnOpen = function () { 'use strict'; this.retry = 0; console.log('**** Websocket Connected ****'); this.clock = new Date(); }; this.handleWebsocketMessage = function (message) { let command; try { command = JSON.parse(message.data); } catch (e) { /* Do nothing */ } if (command) this.handleData.call(this, command); }; this.handleWebsocketClose = function () { console.error('WebSocket Connection Closed.'); const now = new Date(); // const uptime = now.getTime() - this.clock.getTime(); const uptime = 1; console.log('Socket alive for', uptime / 1000); const self = this; console.log('Waiting ', 15000); this.timer = setTimeout(function () { self.startWebSocket(); }, 15000); }; this.startWebSocket(); };