nodePong/client/lib/socket/socketio_handler.js

88 lines
2.2 KiB
JavaScript
Raw Normal View History

2016-02-14 00:49:19 +11:00
/**
* @file SocketIO.js
* @author frtk
*/
NPGClient.SocketIO = {
// Connection to server
conn_nAttempts: 0,
conn_IntervalID: 0,
socket: {},
isConnected: false,
// start connection loop
initConnectLoop: function() {
var self = this;
console.log();
self.startConnectLoop();
},
2016-02-14 14:37:31 +11:00
2016-02-14 00:49:19 +11:00
// start connection loop
startConnectLoop: function() {
var self = this;
self.conn_IntervalID = setInterval(function() { self.connect(); }, 1500);
},
2016-02-14 14:37:31 +11:00
2016-02-14 00:49:19 +11:00
// stop connection loop
stopConnectLoop: function() {
var self = this;
clearInterval(self.conn_IntervalID);
self.conn_IntervalID = 0;
self.conn_nAttempts = 0;
},
2016-02-14 14:37:31 +11:00
2016-02-14 00:49:19 +11:00
// connect socket
connect: function() {
var self = this;
// check for connection
if (self.isConnected) {
return false;
}
//
if (typeof io !== 'object') {
//console.log('[NPGClient.SocketIO] io object is unknown');
}
if ((typeof self.socket.socket === 'undefined')) {
console.log('[NPGClient.SocketIO] attempting server connection...');
self.socket = io.connect();
self.defineSocketMsgs();
} else if (!self.socket.socket.connected && !self.socket.socket.connecting) {
console.log('[NPGClient.SocketIO] attempting server connection...');
self.socket.socket.connect();
}
},
2016-02-14 14:37:31 +11:00
2016-02-14 00:49:19 +11:00
// Define Socket Messages
defineSocketMsgs: function() {
var self = this;
if (typeof self.socket === 'undefined') {
return false;
}
console.log('[NPGClient.SocketIO] deploying socket object features.');
// 'connecting'
self.socket.on('connecting', function () {
console.log('[NPGClient.SocketIO] connecting ...');
});
// 'connect'
self.socket.on('connect', function() {
console.log('[NPGClient.SocketIO] connected to server');
self.stopConnectLoop();
self.isConnected = true;
});
// 'disconnect'
self.socket.on('disconnect', function() {
console.log('[NPGClient.SocketIO] > Server: socket disconnected.');
self.startConnectLoop();
self.isConnected = false;
});
2016-02-14 14:37:31 +11:00
},
// send message to server
sendMsg: function(name, data) {
var self = this;
self.socket.emit(name, data);
2016-02-14 00:49:19 +11:00
}
};