Friday, August 5, 2011

Chat Server

var net = require('net');
var sockets = [];
net.createServer(function(socket) {
sockets.push(socket);

socket.on('data', function(data) {
console.log(socket.remoteAddress + ' - ' + data);
for(var i = 0; i < sockets.length; i++) {
if (sockets[i] != socket)
sockets[i].write(data);
}
});

socket.on('end', function() {
sockets.splice(sockets.indexOf(socket), 1);
})

}).listen(9000, 'localhost');


What's going on here?
  • Line 2 creates an array for us to store a reference to the sockets
  • Line 3 creates the socket server where we pass in our callback function
  • Line 4 adds the new socket to our array
  • Lines 5-11 writes the incoming data to each socket in our listen
  • Lines 12-14 removes any dead sockets - why can we do this without locking?