On Github theosp / multiplayer-pong-presentation
Node.js serves as both the parser and the server - our web-app need no http server
fs.readFile('./file', function (err, data) { if (err) throw err; console.log(data); });
JS Idioms
setTimeout(function () { // do stuffs }, 1000);
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(80, '127.0.0.1');
$ node hello.js
$ npm publish
Aug 2013
Nov 2013
Mar 2014
var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send('hello world'); }); app.listen(3000);
var express = require('express'); var app = express(); app.use("/shared_dir", express.directory("/directory")); app.listen(3000);
var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); });
<script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://localhost'); socket.on('news', function (data) { console.log(data); socket.emit('my other event', { my: 'data' }); }); </script>
$("#up,#down") .bind("touchstart", function (e) { socket.emit("direction", field_id, controller_id, \ controller_side, this.id === "up" ? 1 : -1); }) .bind("touchend", function (e) { socket.emit("direction", field_id, controller_id, \ controller_side, 0); });
socket.on('direction', function (field_id, controller_id, \ side, controller_direction) { // get field_socket var field_socket = getFieldSocket(socket, field_id); if (field_socket === false) { return; } // update controller direction if (typeof controllers[field_id][controller_id] === 'undefined') { return; } controllers[field_id][controller_id].direction = \ controller_direction; var direction = /* ... Sum controllers direction for the given side */; if (direction > 0) { direction = 1; } if (direction < 0) { direction = -1; } field_socket.emit("direction", side, direction); });
socket.on("direction", function (side, direction) { paddle = side === 0 ? pong.leftPaddle : pong.rightPaddle; if (direction === 1) { paddle.moveUp(); } else if (direction === 0) { paddle.stopMoving(); } else { paddle.moveDown(); } });