Improved socket connection for node_helper.

This commit is contained in:
Michael Teeuw
2016-03-30 16:25:24 +02:00
parent 59b339aba5
commit b243d25399
6 changed files with 55 additions and 107 deletions

View File

@@ -6,7 +6,6 @@
*/
var Class = require('../../../js/class.js');
var MMSocket = require('../../../js/socketclient.js');
NodeHelper = Class.extend({
init: function() {
@@ -34,24 +33,6 @@ NodeHelper = Class.extend({
*/
setName: function(name) {
this.name = name;
this.socket();
},
/* socket()
* Returns a socket object. If it doesn't exsist, it's created.
* It also registers the notification callback.
*/
socket: function() {
if (typeof this._socket === 'undefined') {
this._socket = this._socket = new MMSocket(this.name);
}
var self = this;
this._socket.setNotificationCallback(function(notification, payload) {
self.socketNotificationReceived(notification, payload);
});
return this._socket;
},
/* sendSocketNotification(notification, payload)
@@ -61,7 +42,39 @@ NodeHelper = Class.extend({
* argument payload mixed - The payload of the notification.
*/
sendSocketNotification: function(notification, payload) {
this.socket().sendNotification(notification, payload);
this.io.of(this.name).emit(notification, payload);
},
/* setSocketIO(io)
* Sets the socket io object for this module.
* Binds message receiver.
*
* argument io Socket.io - The Socket io object.
*/
setSocketIO: function(io) {
var self = this;
self.io = io;
console.log('Connecting socket for: ' + this.name);
var namespace = this.name;
io.of(namespace).on('connection', function (socket) {
// add a catch all event.
var onevent = socket.onevent;
socket.onevent = function (packet) {
var args = packet.data || [];
onevent.call (this, packet); // original call
packet.data = ["*"].concat(args);
onevent.call(this, packet); // additional call to catch-all
};
// register catch all.
socket.on('*', function (notification, payload) {
if (notification !== '*')
console.log('received message in namespace: ' + namespace);
self.socketNotificationReceived(notification, payload);
});
});
}
});