In this tutorial I’m going to cover creating a basic drawing game with Node.js, Express.js and Socket.io using HTML5 Canvas. This tutorial isn’t meant for beginners of Node.js and assumes you already have Node.js installed on your system. If you’re not too familiar with Express.js it’s a Node.js application framework that allows you to build ReSTful APIs on top of Node.js. Some of the top sites like Myspace, LearnBoost, and Storify are using it for their website and it is definitely worth learning ( not that it will take long to learn it’s very simple if you’re familiar with ReST). Now socket.io can take a bit to pick up on but don’t let that scare you it simply allows us to create realtime applications that are cross browser compatible using the new HTML5 Websocket API. Alright so let’s get started first thing you are going to want to do is use Bash and CD into the directory of your app to install the node packages. To install Express type the following command in your directory.

npm install express

and do the same for socket.io

npm install socket.io

If everything went successful you should now see a new folder inside your directory called “node_modules” this contains the packages we just installed. Now we can begin hacking :)
In your code editor create a new JavaScript file and save it with the name “server.js” this will be our server-side JavaScript that sends the packets of data back and forth between clients. Now add this code to create the server

//Here is where we create the global parameters
//and start listening to 'port', we are creating an express
//server and then binding it to socket.io
var express = require('express'),
	app     = express(),
	server  = require('http').createServer(app),
	io      = require('socket.io').listen(server);
        //we're also going to create another variable to keep track of the clients
        serverClients = {};
//have to server listen to port 1337
server.listen(1337);

Now the next thing we need to do after creating the server is configure express, since this server is also a web server, we need to define the paths to the static files

//configure express paths to load resources when making a GET request
app.use("/css", express.static(__dirname + '/public/styles'));
app.use("/js", express.static(__dirname + '/public/js'));

The next thing to do is setup the main application file so when the client makes a GET request it will load our index.html file in our public directory at our app root (localhost:1337)
We also can add a setting for websockets in case a browser doesn’t support it *cough cough IE* and allow it to fallback to XHR-polling you can find more about polling here.

app.get('/', function (req, res) {
	res.sendfile(__dirname + '/public/index.html');
});
//add setting to use websockets first but if a browser doesn't support websockets fallback to xhr-polling
//browsers that support websockets: http://caniuse.com/websockets
io.set('transports', [ 'websocket', 'xhr-polling' ]);

Now we are going to start creating are socket.io events, each connection goes through these and each event is emitted in the client. We’re going to create events for the connection, when somebody connects and when somebody is drawing

// socket.io events, each connection goes through here
// and each event is emited in the client.
// I created a function to handle each event
io.sockets.on('connection', function(socket){
	socket.on('connect', function(data){
		//call function for connect and send the socket and data
		connect(socket, data);
	});
	//event when a client disconnects from the app
	socket.on('disconnect', function(){
		disconnect(socket);
	});
	//when a client draws a line this event is going to be emitted and sent to all the other sockets (clients)
	socket.on('drawing', function(data){
		updateDrawing(socket, data.image);
	});
});

Now we are going to code the functions that are called when these events are emitted. We will start with the connect and disconnect functions and pass the arguments we sent from the event.

function connect(socket, data){
	//generate clientid
	data.clientId = generateId();
	//save the client to the hash object
	//for quick access, we save this data on the socket
	//with 'socket.set(key, value)'
	//but the only way to pull it back out will be async
	serverClients[socket.id] = data;
}
function disconnect(socket){
	//delete the socket (client) from the hash object
	delete serverClients[socket.id];
}

Now that we added those functions we can create the “updateDrawing” function which is called when the client draws on the canvas. Our client-side is going to create a Data-URL of the image drawn on the canvas after the mouseup or touchend event and then send the data to our server.

function updateDrawing(socket, image){
	//socket.broadcast sends data to everyone besides the sender
	//we are going to send the Data-URL created from our client-side
	socket.broadcast.emit('drawing', {image: image});
}

Now the we can get started on the client-side but first we need to create a public folder inside of our application directory. We then can add the code for our index.html file and as you will probably notice before the body tag closes is the JavaScript file for socket.io and it’s using a relative url. This is because because we are wrapping our HTTP Server in Socket.io and it intercepts the request for “/socket.io/socket.io.js” and sends the correct response automatically. This was a confusing concept at first for me and I was wondering where the JS file was but that’s how it works :)

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<meta name="description" content="A description about your site" />
	<meta name="keywords" content="keywords, separated, by, comma" />
	<title>HTML5 Drawing Game</title>
	<!--[if IE]>
		<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->
</head>
<body>
	<section id="main">
	</section>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
</body>
</html>

After adding that code we can now test our server out, you’re going to want to be in your application directory when you run this and not the public directory.

node server.js

You should see “info – socket.io started” and should now be able to access our index.html file by going to “localhost:1337″. The page should be blank but you can make sure it’s working by going to this url “localhost:1337/socket.io/socket.io.js” and see the JS file or you can use dev tools network tab and make sure the request was successful like this.

That’s about it for the first part of the tutorial if you have any questions or feedback feel free to comment in the box below! Thanks for reading!

You can also find the source code used in the tutorial via github here
https://github.com/joshbedo/drawingTutorial