Skip to content

Instantly share code, notes, and snippets.

@nicholascloud
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicholascloud/603ae8ead6769ad9b8b5 to your computer and use it in GitHub Desktop.
Save nicholascloud/603ae8ead6769ad9b8b5 to your computer and use it in GitHub Desktop.
var events = require('events');
var net = require('net');
var channel = new events.EventEmitter();
var i = 0;
var subscriptions;
var clients = {};
var clientID = 0;
channel.on('join', function (e) {
clients[e.id] = e.client;
console.log('client joined', e.id);
});
channel.on('broadcast', function (e) { // lower listener
Object.keys(clients).map(Number).forEach(function (id) {
// don't send message to myself
if (e.from === id) {
return;
}
var client = clients[id];
client.write(e.data + '\r\n');
console.log('message sent to', id, e.data);
});
});
var server = net.createServer(function (client) {
var id = (clientID += 1);
// channel is acting as a kind of service bus
channel.emit('join', {id: id, client: client});
client.on('data', function (data) {
channel.emit('broadcast', {from: id, data: data.toString()});
});
});
server.listen(7000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment