Using Node.js and your phone to control a Browser game

by Pascal Rettig posted Aug 24, 2011

This past week I undertook a pretty cool project as the Intern here at Cykod. We were wondering how easily a smart phone –specifically using its gyroscopes and accelerometers– could be used as a controller for a multi-player game on a larger screen. With a bit of Node.js and HTML5 magic, it turned out to be pretty simple.


We want to use a desktop (laptop, iPad, etc. something with a bigger screen that multiple players can easily look at) connection to act as the common game space. Once that screen is initialized, each player connects to a specific URL in their phone browser that links them to that game instance. We'll follow this basic outline:


The proof-of-concept full game is up at  


The Technology

Node.js is what makes this project possible. Built on Google's V8 Javascript Engine, Node.js is a server environment written in -wait for it- JavaScript. I started this project with zero knowledge of writing a server or what it would take, and Node made it super easy. Unfortunately, because the Node.js project is growing so quickly, up-to-date documentation with current-version examples can be lacking.
A Node.js module, adds multiple levels of socket support, accommodating nearly every browser. This allows Node.js to quickly communicate with the browser similar to the way AJAX would, but with less overhead. does not yet seem to support the updated Websocket Spec deployed in the latest Chrome and Firefox. As soon as it does, performance will be significantly smoother compared to the current default of XHR Long polling.  Now supported in the newest version of, and controller performance is better.

Mobile Phone Orientation
Nearly all smart phones on the market have some sort of accelerometer or gyroscope in them. The phone parses this information and makes it accessible in the browser. The HTML5 DeviceOrienation and DeviceMotion events allow us to take advantage of this. You can read more about it at HTML5 Rocks. (Fun Fact: The native Android browser does not support access of this data. A third party browser like Firefox is needed)

Building the server

The actions performed by the mobile phone and desktop will be completely independent of each other, communicating only through the server (app.js). The best way to do this is through two different html files. We could embed all the code into one large file, but that would overly complicate our simple proof of concept. Create index.html (for the desktop), and mobile.html (for the phone).

Room Structure
Each game instance needs a desktop screen and at least one mobile device to communicate. We don't want any outside interference, so we'll create a new game instance for each desktop screen. We'll refer to a game instance as a room. Each room contains a desktop and an unknown number of mobile connections. For clarity's sake (and to help distinguish between different rooms), we'll also include a room id. Room Structure:


//An array to store the existing rooms
var rooms = [];
function room(roomSocket, roomId){
  this.roomSocket = roomSocket;  //Stores the socket for the desktop connection
  this.roomId = roomId;          //The room id/name. A unique string that links desktop to mobile
  this.mobileSockets = [];       //A list of all the mobile connections

Definition: A socket is how we refer to a single connection. So for every device connected to the server, a socket is created. Node.js and streamline this process, automatically creating and destroying sockets as needed. This continually simplifies our room management.

New Connections
When a new socket is created (anytime a user visits index.html or mobile.html), we want to notify app.js so it can either:

A) Create a new room (if index.html is sending the data),


//This sends the signal 'new room' to the server, along with data containing the room name id. For live deployment, this should be a random string. See the full documentation for example socket.emit('new room', { room: “lolcats”});



//The receiving end of 'new room'
socket.on("new room", function(data){
  //Pushes a new room instance, storing the desktop connection as the roomSocket and ("lolcats") as the roomId
  rooms.push(new room(socket,;

Awesome! So we have a new room object being created and stored each time a new desktop connection is established. For efficiency's sake, we want to monitor any lost connections and delete those rooms, but we'll get into that shortly.


B) Or add a user to a room instance (if mobile.html is sending the data)


socket.emit('connect mobile', { room: getUrlVars()["id"]}, function(data){
  if(data.registered = true){
    registered = true;

Similar to a new desktop connection, mobile.html sends an emit('connect mobile') to app.js. We also pass along the id parameter from the URL (mobile.html?id=RoomName) to specify which room this mobile user should belong to. Lastly, a callback function informs the mobile user that they have connected successfully, and can now transmit data.


socket.on("connect mobile", function(data, fn){
  var desktopRoom = null;

  //Cycle through all the rooms and find the room with the same roomId as our mobile device
  for(var i = 0; i < rooms.length; i++){
    if(rooms[i].roomId =={
      desktopRoom = i;

  if(desktopRoom !== null){

    //Store the position of our room that this mobile device belongs to
    socket.set('roomi', desktopRoom, function(){})

    //Return the callback as true
    fn({registered: true});

    //Access the room that this socket belongs to, and emit directly to the index.html to 'add user' with the socketId as a unique indentifier.
    rooms[].roomSocket.emit('add user',, data);
    //Callback returns false with an error
    fn({registered: false, error: "No live desktop connection found"});

The server searches through the array of rooms to locate the correct one. Once we've identified the room by its name, it is saved in desktopRoom. After double checkingagainst a null value to ensure we have located a room, the mobile socket is pushed into the room[id].mobileSocket array. The socket.set method is then used to store data directly in the socket. We save the room's position in the array. With this value, we can easily access the appropriate room without having to search the array each time. The callback is returned as true if successful, or false with an error message.

Lost connections
But what happens when we lose a connection? has a built in 'disconnect' function that is called when a socket disconnects. We start by testing for the existence of Because we only set that value for the mobile connections, we know instantly the type of connection.


socket.on("disconnect", function(){
  var destroyThis = null;
f(typeof == 'undefined'){

    //The lost socket is a room

    //Search through all the rooms and remove the socket which matches our disconnected id
    for(var i in rooms){
      if(rooms[i] =={
        destroyThis = rooms[i];

    if(destroyThis !== null){ rooms.splice(destroyThis, 1);}

    //Lost socket is a mobile connections

    //Sort through the mobile sockets for that particular room, and remove accordingly
    var roomId =;
    for(var i in rooms[roomId].mobileSockets){
      if(rooms[roomId].mobileSockets[i] == socket){
        destroyThis = i;

    if(destroyThis !== null){rooms[roomId].mobileSockets.splice(destroyThis, 1);}

    //alert the room that this user was a member of
    rooms[roomId].roomSocket.emit('remove user',;

We now have a fully functioning Node.js server that handles all connections, disconnections, and stores our data in easy to parse room structures.

Updating the Tilt Data

With the connection established, we can easily send tilt data from the mobile to desktop side. This is covered in much better detail over at HTML5 Rocks, so we'll skip to the Node stuff.


function deviceOrientationHandler(tiltLR, tiltFB, dir, motionUD) {
    socket.emit('update movement', { tilt_LR: Math.round(tiltLR), tilt_FB: Math.round(tiltFB)});

This function will run every time the phone gets new mobile tilt data. We're really only interested in the tiltLR (Left Right), and tilfFB (front back). Read through the HTML5 Rocks for more info. app.js receives this data and immediately forwards it along to the desktop corresponding to our mobibile device.


//Update the position socket.on("update movement", function(data){
  if(typeof !== 'undefined'){
    if(typeof rooms[] !== 'undefined'){
      rooms[].roomSocket.emit('update position',, data);

Because mobile.html transmits data after a connection is established, there is no error checking to make sure the index.html counterpart still exists. Our 'update movement' performs this check to ensure the desktop connection still exits. It emits data directly to the correct room in the 'update position' signal.


socket.on('update position', function(socketId, data){}

The server will then signal index.html and call the socket.on("update position") . This passes all our tilt data to the desktop client, leaving the world wide open for awesome canvas implementations.

I won't be going into the canvas game aspects, but the example code and a basic version of canvas game play is available on Github. You can also see our language learning game implementation, Super Space Words .