Created
November 8, 2010 01:08
-
-
Save ggoodale/667257 to your computer and use it in GitHub Desktop.
Node.js example #2 From Deploy 2010
This file contains hidden or 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 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