Skip to content

Instantly share code, notes, and snippets.

@dodops
Created April 5, 2015 01:29
Show Gist options
  • Save dodops/2fee18bdf7ae14c49994 to your computer and use it in GitHub Desktop.
Save dodops/2fee18bdf7ae14c49994 to your computer and use it in GitHub Desktop.
chat_server.js
var net = require('net');
var chatServer = net.createServer(), clientList = [];
chatServer.on('connection', function(client){
client.name = client.remotePort;
client.write('Hi ' + client.name + '!\n');
clientList.push(client);
console.log("connected clients: " + clientList.length);
client.on('data', function(data){
broadcast(data, client);
});
client.on('end', function(){
clientList.splice(clientList.indexOf(client), 1)
});
client.on('error', function(e){
console.log(e);
});
function broadcast(message, client){
var cleanup = [];
for(var i = 0; i < clientList.length; i+=1){
if(client !== clientList[i]){
if(clientList[i].writable) {
clientList[i].write(client.name + " says: " + message);
} else {
cleanup.push(clientList[i]);
clientList[i].destroy();
}
}
}
for (var i = 0; i < cleanup.length; i+=1) {
clientList.splice(clientList.indexOf(cleanup[i]), 1);
};
}
});
chatServer.listen(9000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment