-
-
Save nicholascloud/603ae8ead6769ad9b8b5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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