How to use Socket.IO properly with Express Framework in Node.js

How to use Socket.IO properly with Express Framework in Node.js

Sockets abstract the network into something easier to handle and to work with. Socket.IO enables real-time bidirectional event-based communication, it works on every platform, browser or device, focusing equally on reliability and speed.

Socket.IO handles graceful degradation for you to numerous technical alternatives to get bi-directional near-time communication flowing (web sockets, ajax long polling, flash, etc). Besides, it handles browser inconsistencies and varying support levels for you and is a lot of easier to work with instead of vanilla web sockets, at least at the moment.

In this article, you'll learn how to put to work Socket.IO and Express Framework, the minimalist web framework easily in a couple of minutes.

Requirements

Install Express on your project executing the following command in your Node.js console:

npm install express --save

Likewise, install Socket.IO in your project executing the following command in your Node.js console:

npm install socket.io --save

And you're ready to get started!

Implementation

In order to work correctly with Express and Socket.IO we need to require the http module of node.js as it will be at charge of the server. The variable server is the returned object of the createServer method (which receives the express app as first parameter) and in turn, the server variable will be used as first parameter in the listen method of the socket.io module.

Create a file (named server.js) wherever you want and add the following code on it:

Note: to start the server by itself, the listen method needs to be executed from the server variable, not the app itself. You need to understand this to prevent known errors like "SocketIO: err_connection_refused".

var http = require('http');
var express = require('express');
var app = express();

var server = http.createServer(app);
// Pass a http.Server instance to the listen method
var io = require('socket.io').listen(server);

// The server should start listening
server.listen(80);

// Register the index route of your app that returns the HTML file
app.get('/', function (req, res) {
    console.log("Homepage");
    res.sendFile(__dirname + '/index.html');
});

// Expose the node_modules folder as static resources (to access socket.io.js in the browser)
app.use('/static', express.static('node_modules'));

// Handle connection
io.on('connection', function (socket) {
    console.log("Connected succesfully to the socket ...");

    var news = [
        { title: 'The cure of the Sadness is to play Videogames',date:'04.10.2016'},
        { title: 'Batman saves Racoon City, the Joker is infected once again',date:'05.10.2016'},
        { title: "Deadpool doesn't want to do a third part of the franchise",date:'05.10.2016'},
        { title: 'Quicksilver demand Warner Bros. due to plagiarism with Speedy Gonzales',date:'04.10.2016'},
    ];

    // Send news on the socket
    socket.emit('news', news);

    socket.on('my other event', function (data) {
        console.log(data);
    });
});

Our server side code should work at the first intent. As you can see, when there's an incoming connection from the browser to the socket, we are going to print the "Connected succesfully to the socket" message in the Node console and we are going to send some information to the active socket in the browser (in this case we are going to send a simple object with some "news" to be rendered in the index.html file).

Note: the app.use('/static') line, will expose the node_modules folder in the server, this in order to access the socket.io.js file in index.html. You can delete this line and copy the socket.io.js from the socket.io folder and copy it directly in the same directory where index.html is located, in case you don't want to expose this folder.

Of the same way, we have just added the index route (/) with a file as returned value (index.html) which will contain the following code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Socket.io</title>
    </head>
    <body>
        <h1>Express and socket.io</h1>
        <div id="news-list"></div>
        <script src="static/socket.io/node_modules/socket.io-client/socket.io.js"></script>
        <script>
            var socket = io('http://localhost:80');

            socket.on('news', function (data) {
                var div = document.getElementById("news-list");
                console.log("Rendering news : ",data);

                for(var i = 0;i < data.length;i++){
                    var newsItem = data[i];
                    div.innerHTML += "<h3>" + newsItem.title + ' <small>'+ newsItem.date + "</small></h3><br>";
                }

                socket.emit('my other event', { my: 'data' });
            });
        </script>
    </body>
</html>

The declaration of the socket variable will open a connection between the browser and the server (via socket), that will cause the execution of the on("connection") method in our server.js file and will send information that will be manipulated in the view.

Now, you just need to test it ! execute the server.js file executing the following command in your node console:

node server.js

Navigate in your favorite browser to http://localhost:80 and the socket connection should be working properly (and the news will be drawn, as planned in our logic):

Socket.IO and Express Framework socket

Have fun !

Become a more social person