diff --git a/networking/server.js b/networking/server.js new file mode 100644 index 0000000..b6db608 --- /dev/null +++ b/networking/server.js @@ -0,0 +1,136 @@ +var http = require('http'), + io = require('socket.io'), + fs = require('fs'), + Box2D = require('./box2d.js'); + +eval(fs.readFileSync('common.js') + ''); + +var clients = []; + +function update() { + world.Step(1 / 60, 10, 10); + world.ClearForces(); +} + +setInterval(update, 1000 / 60); +setInterval(updateClients, 100); + +function updateClients() { + var body = world.GetBodyList(); + var update = {}; + var isUpdateNeeded = false; + + do { + var userData = body.GetUserData(); + + if(userData && userData.bodyId && body.IsAwake()){ + update[userData.bodyId] = { + p: body.GetPosition(), + a: body.GetAngle(), + v: body.GetLinearVelocity(), + }; + isUpdateNeeded = true; + } + } while (body = body.GetNext()); + + + if(isUpdateNeeded) { + sendToClients('world-update', update); + } +} + +function sendToClients(message, data) { + var packet = { + m: message, + d: data + } + //console.log(JSON.stringify(packet)); + for (var i = 0; i < clients.length; i++) { + clients[i].send(JSON.stringify(packet)); + } +} + +function pong(client, data) { + var packet = { + m: 'pong', + d: data + } + client.send(JSON.stringify(packet)); +} + +setupWorld(); +//update(); + +// SOCKETS + +var server = http.createServer( + function(req, res){ + res.writeHead(200, {'Content-Type': 'text/html'}); + res.end('