Created
October 5, 2014 03:10
-
-
Save aweary/2721832fc27e97c98fdd to your computer and use it in GitHub Desktop.
3.11 - logging added
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) { | |
console.log('join fired'); | |
channel.clients[id] = client; | |
this.subscriptions[id] = function(senderId, message) { | |
console.log('broadcast fired'); | |
//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() { | |
console.log('connect fired'); | |
//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) { | |
console.log('data fired'); | |
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