Skip to content

Instantly share code, notes, and snippets.

@ggoodale
Created November 8, 2010 01:08
Show Gist options
  • Save ggoodale/667257 to your computer and use it in GitHub Desktop.
Save ggoodale/667257 to your computer and use it in GitHub Desktop.
Node.js example #2 From Deploy 2010
var net = require('net'), fs = require('fs'), _ = require('./underscore-min')._;
// Our active connections
var connections = {};
var doc = fs.readFileSync('lyrics.txt', 'utf8').split(" ");
var word = 0;
var intervalId = null;
var sing = function() {
if ((word >= doc.length || _.size(connections) == 0) && intervalId != null) {
clearInterval(intervalId);
word = 0;
intervalId = null;
} else {
_(connections).each(function(receiver) { receiver.write(doc[word] + " "); });
word++;
}
}
var server = net.createServer(function(sock) {
sock.setTimeout(0)
sock.setEncoding("utf8");
connections[sock.remotePort] = sock; // Store a reference to the new client
sock.on('data', function(data) {
if (data.match(/^sing\n$/i) && !intervalId) {
intervalId = setInterval(sing, 350); // Sing!
} else {
_.each(connections, function(receiver) {
if (sock !== receiver) { receiver.write(data); } // Send new data to all other sockets
});
}
});
sock.on('close', function() { delete connections[this.remotePort]; });
});
server.listen(8124, "0.0.0.0");
console.log("Server started");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment