var WEBSOCKET = function(model) { var wsUrl = ['localhost','silvrtree.co.uk']; var wsPort = '9000'; let useUrl = 0; if ('https:' === document.location.protocol) { wsUrl = 'wss://' + wsUrl[useUrl] + ''; wsPort = ''; } else { //wsUrl = 'ws://localhost:3001'; wsUrl = 'ws://' + wsUrl[useUrl] + ''; wsPort = ''; } this.socket = null; this.timer = 0; this.clock = null; this.startWebSocket = function() { 'use strict'; var url = (wsPort === '') ? wsUrl : wsUrl + ':' + wsPort; console.log('Starting socket', url); var 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) { var 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.'); var now = new Date(); var uptime = now.getTime() - this.clock.getTime(); console.log('Socket alive for', uptime / 1000); var self = this; console.log('Waiting ', 5000); this.timer = setTimeout(function() {self.startWebSocket();},5000); }; this.startWebSocket(); };