Last active
August 29, 2015 14:07
-
-
Save aweary/b9d917f8c9017228c02d to your computer and use it in GitHub Desktop.
Node.JS in Action, example 3.11
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(); | |
channel.clients = {}; | |
channel.subscriptions = {}; | |
//Add a listener for the join event that stores a user’s client object, | |
//allowing the application to send data back to the user. | |
channel.on('join', function(id, client) { | |
this.clients[id] = client; | |
this.subscriptions[id] = function(senderId, message) { | |
//ignore data if it’s been directly broadcast by the user. | |
if (id != senderId) { | |
this.clients[id].write(message); | |
} | |
} | |
//Add a listener, specific to the current user, for the broadcast event. | |
this.on('broadcast', this.subscriptions[id]); | |
}); | |
var server = net.createServer(function(client) { | |
var id = client.remoteAddress + ':' + client.remotePort; | |
client.on('connect', function() { | |
//Emit a join event when a user connects to the server, specifying the user ID and client object. | |
channel.emit('join', id, client); | |
}); | |
client.on('data', function(data) { | |
data = data.toString(); | |
//Emit a channel broadcast event, specifying the user ID and message, when any user sends data. | |
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