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...