Skip to content

Instantly share code, notes, and snippets.

@sang4lv
Last active December 21, 2015 12:48
Show Gist options
  • Save sang4lv/6307834 to your computer and use it in GitHub Desktop.
Save sang4lv/6307834 to your computer and use it in GitHub Desktop.
var net = require('net');
var events = require('events');
var channel = new events.EventEmitter();
channel.clients = {};
channel.subscriptions = {};
channel.on('join', function(id, client) {
this.clients[id] = client;
this.subscriptions[id] = function(senderId, message) {
for(var index in this.clients) {
if(index !== senderId) this.clients[index].write(message);
}
/*
//Originally
if(id !== senderId) {
this.clients[id].write(message);
}*/
};
this.on('broadcast', this.subscriptions[id]);
});
net.createServer(function (client) {
var id = client.remoteAddress + ":" + client.remotePort;
client.on('connect', function() {
console.log("Why won't this line even run?");
channel.emit('join', id, client);
});
client.on('data', function(data) {
data = data.toString();
channel.emit('broadcast', id, data);
});
}).listen(3002);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment