Socket.io

Socket.io

Socket.io is our favorite engine for building fast real-time applications. Here’s why we love it:

  • Easy to use node module on the server side and javascript library for the client.
  • Works well with Express and follows similar middleware patterns (.on, .use).
  • Uses web sockets, but degrades gracefully to other methods when not available (polling).
  • Built-in support for name spacing, rooms, and authentication.

Let’s look at a basic example of how to build a simple Express web server with Socket.io handling the real-time communication. First, open a new file in your favorite text editor called “server.js” and add the following lines of code:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

Here we’ve done three things:

  • Create an instance of the Express web server.
  • Create an http listener and attach Express.
  • Create a Socket.io server and attach it to the http listener

Express will handle most of the http requests, but any requests to “/socket.io/” will be passed through to the Socket.io engine.

Next we need to serve out some html to the client:

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

Socket.io needs to know what to do with incoming messages. For our chat room, we are going to send the incoming message out to everyone who is connected, so in the “connection” event handler, we’ll attach a new handler for when “chat message” messages are received:

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

Then we tell our server to start listening on port 3000:

http.listen(3000, function(){
    console.log('listening on *:3000');
});

That’s it for server.js, save it, and now our server is ready to run. However, before we can run, we still need to build our “index.html” file that is being served out:

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cstyle%3E%0A%20%20%20%20%20%20*%20%7B%20margin%3A%200%3B%20padding%3A%200%3B%20box-sizing%3A%20border-box%3B%20%7D%0A%20%20%20%20%20%20body%20%7B%20font%3A%2013px%20Helvetica%2C%20Arial%3B%20%7D%0A%20%20%20%20%20%20form%20%7B%20background%3A%20%23000%3B%20padding%3A%203px%3B%20position%3A%20fixed%3B%20bottom%3A%200%3B%20width%3A%20100%25%3B%20%7D%0A%20%20%20%20%20%20form%20input%20%7B%20border%3A%200%3B%20padding%3A%2010px%3B%20width%3A%2090%25%3B%20margin-right%3A%20.5%25%3B%20%7D%0A%20%20%20%20%20%20form%20button%20%7B%20width%3A%209%25%3B%20background%3A%20rgb(130%2C%20224%2C%20255)%3B%20border%3A%20none%3B%20padding%3A%2010px%3B%20%7D%0A%20%20%20%20%20%20%23messages%20%7B%20list-style-type%3A%20none%3B%20margin%3A%200%3B%20padding%3A%200%3B%20%7D%0A%20%20%20%20%20%20%23messages%20li%20%7B%20padding%3A%205px%2010px%3B%20%7D%0A%20%20%20%20%20%20%23messages%20li%3Anth-child(odd)%20%7B%20background%3A%20%23eee%3B%20%7D%0A%20%20%20%20%3C%2Fstyle%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;style&gt;" title="&lt;style&gt;" />

  </head>
  <body>
    
<ul id="messages"></ul>


<form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>

    <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22https%3A%2F%2Fcdn.socket.io%2Fsocket.io-1.2.0.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
    <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22http%3A%2F%2Fcode.jquery.com%2Fjquery-1.11.1.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
    <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3E%0A%20%20%20%20%20%20var%20socket%20%3D%20io()%3B%0A%20%20%20%20%20%20%24('form').submit(function()%7B%0A%20%20%20%20%20%20%20%20socket.emit('chat%20message'%2C%20%24('%23m').val())%3B%0A%20%20%20%20%20%20%20%20%24('%23m').val('')%3B%0A%20%20%20%20%20%20%20%20return%20false%3B%0A%20%20%20%20%20%20%7D)%3B%0A%20%20%20%20%20%20socket.on('chat%20message'%2C%20function(msg)%7B%0A%20%20%20%20%20%20%20%20%24('%23messages').append(%24('%3C%2Fp%3E%0A%3Cli%3E').text(msg))%3B%0A%20%20%20%20%20%20%7D)%3B%0A%20%20%20%20%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
  </body>
</html>

As you can see, its a basic chat window with a text input and send button at the bottom. We’ve also set up two basic javascript events:

  • Send the message in the text input when the Send button is pressed.
  • Append the message to the div when a “chat message” is received from the server.

To run the example, install the required modules and execute with node:

npm install socket.io
npm install express
node server.js

And point your browser at http://localhost:3000

Full source for this example can be found here.

Submit a Comment

Your email address will not be published. Required fields are marked *