Skip to content

Instantly share code, notes, and snippets.

@SergeyNarozhny
Created July 21, 2015 14:16
Show Gist options
  • Save SergeyNarozhny/4d23731feb1fd7566308 to your computer and use it in GitHub Desktop.
Save SergeyNarozhny/4d23731feb1fd7566308 to your computer and use it in GitHub Desktop.
Simple event subscription pattern in NodeJS
var events = require('events'),
net = require('net'),
channel = new events.EventEmitter();
channel.clients = {};
channel.subscriptions = {};
// Add listener on join event
// we save client user object and send
channel.on('join', function(id, client) {
this.clients[id] = client;
this.subscriptions[id] = function(senderId, message) {
// ignore from user himself
if (id != senderId)
{
this.clients[id].write(message);
}
}
this.on('broadcast', this.subscriptions[id]);
});
var server = net.createServer(function(client){
var id = client.remoteAddress + ':' + client.remotePort;
client.on('connect', function(){
// Emit join event after user connect
channel.emit('join', id, client);
});
client.on('data', function(data) {
data = data.toString();
// Emit broadcast event for channel,
// when user sends a message
channel.emit('broadcast', id, data);
});
});
server.listen(8888);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment