Created
March 15, 2010 14:59
-
-
Save harryf/332911 to your computer and use it in GitHub Desktop.
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
http = require('http'); | |
querystring = require('querystring'); | |
sys = require('sys'); | |
/* Display the index page */ | |
function showIndex(req, res) { | |
// Write the static data | |
res.write('<html>'); | |
res.write('<h1>local.ch Töggeli Server</h1>'); | |
res.write('<p>You want to play töggeli? Input your name to add yourself '); | |
res.write('to the queue!</p>'); | |
res.write('<form action="/" method="post">'); | |
res.write('<input type="text" name="name" />'); | |
res.write('<input type="submit" value="Add to queue" />') | |
res.write('</form>'); | |
res.write('</html>'); | |
// Close the connection | |
res.close(); | |
} | |
/* Add someone to the queue */ | |
var event = new process.EventEmitter(); // Use this event to synchronize | |
var players = []; // Save the waiting players here | |
function addToQueue(req, res, parameters) { | |
function playersReady() { | |
// Show the players | |
res.write('Hi ' + parameters['name'] + '! You are playing with:'); | |
res.write('<ul>'); | |
for (var i = 0; i < players.length; i++ ) { | |
res.write('<li>' + players[i] + '</li>'); | |
} | |
res.write('</ul>'); | |
// Alert the user in the browser | |
res.write('<script type="text/javascript">alert("4 players are ready!")</script>'); | |
// We are finished, close the connection | |
res.close(); | |
} | |
// Give the user a message | |
res.write('Hello, ' + parameters['name'] + '!<br/>'); | |
res.write('You were added to the queue. Please don\'t close this window,'); | |
res.write('you will be alerted as soon as there are enough players.'); | |
players.push(parameters['name']); | |
/* TODO: Work with the event here */ | |
event.addListener("gameon", playersReady); | |
if ( players.length == 4 ) { | |
event.emit("gameon"); | |
players = []; | |
event.removeAllListeners(); | |
} | |
// Note that the connection is not closed here - this is a long | |
// polling request! | |
} | |
/* Create the HTTP server */ | |
http.createServer(function (req,res) { | |
// Start the output | |
res.writeHeader(200, { 'Content-type': 'text/html'}); | |
// Call the correct handler depending on the HTTP method. | |
if (req.method == "GET") { | |
showIndex(req, res); | |
} else { | |
// Parse the incoming POST body | |
var body = ""; | |
req.addListener("data", function(chunk) { | |
body += chunk; | |
}); | |
req.addListener("end", function() { | |
var values = querystring.parse(body); | |
addToQueue(req, res, values); | |
}); | |
} | |
}).listen(8000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment