Getting started with node.js and socket.io


Getting started with node.js and socket.io

I’ve been thinking of creating an HTML5 game and looking at the technology I’d need for it. I needed something to handle real-time communication for the backend and it looked like one of the leading contenders was node.js along with socket.io. I started searching for a tutorial to get started, and while I found a few, many were out of date. So I’m taking what I learned and describing it here.We’re going to build a simple site that reports on the number of clients connected. As clients come and go the number of connected clients will increase or decrease automatically.

Install

Before we start, you’ll notice that I list version numbers for everything. I do that because Node.js and many of the libraries you’ll use are changing (improving) constantly. It’s likely that a year or two after writing this that some of the code won’t function if you’re using newer versions. You don’t need to install the versions listed here, but just be aware that if you’re using a different version that things may not work as expected.

Let’s get started. First off, we’ll need to install Node.js:

If you’re using OSX, do not install node.js using brew. It’s buggy and will cause all sorts of problems down the line. Install using the .pkg file on the node.js site or install using source.

Depending on your OS and your method of install, Node.js may have come bundled with npm (the Node.js package manager). You’re going to need it. You can find out if you have it by, after installing node.js, typing npm into the console. If you see something along the lines of “command not found” then you’ll need to install npm too:

Now we’ll need to install a few Node.js packages. There are many, many packages out there to speed your development along and I recommend learning about them. In the interest of keeping this tutorial simple, we’re going install as few things as possible. All we’ll need is express (a simple web framework for node) and socket.io:

  • sudo npm install express@2.5.9
  • sudo npm install socket.io@0.9.6

(You can leave off the @version to install the latest and greatest version of a package.)

Code

As mentioned earlier, we’re making a simple app that just reports the number of clients (web browsers) connected to it. And we’ll only need a couple files to do it: a javascript file for node.js, and an html file for the client. You won’t need any fancy subdirectories for this, just these two files:

  • connectionCounter.js
  • index.html

connectionCounter.js

We’ll start by creating connectionCounter.js, the node.js portion of our app:

var app = require(‘express’).createServer();
var io = require(‘socket.io’).listen(app);
app.listen(4000);

app.get(‘/’, function(request, response){
response.sendfile(__dirname + “/index.html”);
});

var activeClients = 0;

io.sockets.on(‘connection’, function(socket){clientConnect(socket)});

function clientConnect(socket){
activeClients +=1;
io.sockets.emit(‘message’, {clients:activeClients});
socket.on(‘disconnect’, function(){clientDisconnect()});
}

function clientDisconnect(){
activeClients -=1;
io.sockets.emit(‘message’, {clients:activeClients});
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var app = require(‘express’).createServer();
var io = require(‘socket.io’).listen(app);
app.listen(4000);
app.get(‘/’, function(request, response){
  response.sendfile(__dirname + “/index.html”);
});
var activeClients = 0;
io.sockets.on(‘connection’, function(socket){clientConnect(socket)});
function clientConnect(socket){
  activeClients +=1;
  io.sockets.emit(‘message’, {clients:activeClients});
  socket.on(‘disconnect’, function(){clientDisconnect()});
}
function clientDisconnect(){
  activeClients -=1;
  io.sockets.emit(‘message’, {clients:activeClients});
}

 

index.html

Now we’ll create the index.html file that gets served up to anyone visiting the web server:

 

<!DOCTYPE html>
<html>
<head>
<title>Connection Counter</title>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js”></script&gt;
<script src=”/socket.io/socket.io.js”></script>
<script>
function msgReceived(msg){
$clientCounter.html(msg.clients);
}

$(document).ready(function () {
$clientCounter = $(“#client_count”)

var socket = io.connect(‘http://localhost:4000&#8217;);
socket.on(‘message’, function(msg){msgReceived(msg)});
});
</script>
</head>
<body>
<p><span id=”client_count”>0</span> connected clients</p>
</body>
</html>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
  <head>
    <title>Connection Counter</title>
    <script src=”/socket.io/socket.io.js”></script>
    <script>
      function msgReceived(msg){
        $clientCounter.html(msg.clients);
      }
      $(document).ready(function () {
        $clientCounter = $(“#client_count”)
        var socket = io.connect(‘http://localhost:4000&#8217;);
        socket.on(‘message’, function(msg){msgReceived(msg)});
      });
    </script>
  </head>
  <body>
    <p><span id=”client_count”>0</span> connected clients</p>
</body>
</html>

 

Run

 

Let’s try running it!

Bring up your command line tool and get yourself to where you’ve saved the connectionCounter.js and index.html files. We’ll just need one simple command to get things rolling:

 

$ node connectionCounter.js
1
$ node connectionCounter.js

 

Assuming everything is working, you should see a single line of output:

 

info – socket.io started
1
info – socket.io started

 

Success! Now open your web browser of choice and navigate to: http://localhost:4000/. You should see:

1 connected clients

Open a new tab and again go to: http://localhost:4000/. You should see:

2 connected clients

Go back to the first tab and, viola! 2 connected clients! It updated itself as a new message came through. Try opening and closing tabs and watch as the number changes. It’s simple, but it proves that your tabs are receiving messages from socket.io.

And if you really want to have some fun, watch the server log as you open and close tabs.

I have a favor to ask. I would love to know if this article was useful to you, if it contained too much (or too little!) detail, and if you have any suggestions for improving it. Can you leave a comment with your thoughts?
Copy from http://www.scottblaine.com/2012/getting-started-node-js-socket-io/
Advertisements

2 comments on “Getting started with node.js and socket.io

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s