Running Box2D on server with Node.js via Socket.io

I was kinda bored from the TV this friday and decided that learning a little more on Node.js was more fun. Once able to run a “Hello World” example, I wanted to advance into working on websockets using Socket.IO. Socket.IO is a library for both browser and server which simplifies working with websockets, and at the same time provides fallbacks for older browsers. It was really easy to get started, sending messages between browser and server after short peek into the docs & examples.

Next step was mixing it all up and adding my favorite js library – Box2D.js! I took the code from my Box2D DOM demo in to the main file and created a module from Box2D, exposed  via module.exports. And shockingly the backend-to-frontend-port worked on (almost) the first run! So now instead of the browser animates it’s own DOM objects via JS, it receives CSS for all objects at 30fps from server!

4 browsers, 2 iPhones and 1 iPad, with a lot of boxes animated in sync:

You can download the source here. . All needed libs are embedded, just run ‘node box2dserver.js’ and host the same folder on your localhost. Also remember to change the ‘host’ address in index.html to the one running Node:

window.socket = io.connect('http://<node-server-IP-or-name-here>:8080');