silvrgit/app/js/websocket.js

82 lines
2.0 KiB
JavaScript
Raw Normal View History

2016-10-05 14:09:12 +00:00
var WEBSOCKET = function(model) {
var wsUrl = ['localhost','mdotserver.mybluemix.net','52.211.111.57'];
var wsPort = 9000;
if ('https:' === document.location.protocol) {
wsUrl = 'wss://' + wsUrl[0] + '';
//wsPort = '';
} else {
//wsUrl = 'ws://localhost:3001';
wsUrl = 'ws://' + wsUrl[0] + '';
//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();
};