silvrgit/app/js/websocket.js

83 lines
2.0 KiB
JavaScript
Raw Normal View History

2016-10-05 14:09:12 +00:00
var WEBSOCKET = function(model) {
2016-10-05 14:12:39 +00:00
var wsUrl = ['localhost','silvrtree.co.uk'];
2016-10-05 14:15:37 +00:00
var wsPort = '9000';
2017-04-18 09:06:39 +00:00
let useUrl = 0;
2016-10-05 14:09:12 +00:00
if ('https:' === document.location.protocol) {
2017-04-18 09:06:39 +00:00
wsUrl = 'wss://' + wsUrl[useUrl] + '';
2016-10-05 14:15:06 +00:00
wsPort = '';
2016-10-05 14:09:12 +00:00
} else {
//wsUrl = 'ws://localhost:3001';
2017-04-18 09:06:39 +00:00
wsUrl = 'ws://' + wsUrl[useUrl] + '';
2016-10-05 14:15:06 +00:00
wsPort = '';
2016-10-05 14:09:12 +00:00
}
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();
};