Node Express JS: Socket IO Module Example

Filed Under: Node.js

Before reading post, please go through my previous posts: “Express JS WebApplication with Enide Studio 2014 IDE” and “Express JS Routings with Enide Studio 2014 IDE”.

Introduction to Socket IO

Node JS: Socket IO Module is used to develop Real-time Client-Server Communication applications. It internally uses “WebSocket” Programming model to provide real-time two-way communication between Client and Server.

We can observe that the following Technologies offer WebSocket Programming to implement this kind of applications.

  1. HTML5 WebSocket
  2. Java EE 7 WebSocket API
  3. Node JS:Socket IO Module

Difference between Traditional HTTP and WebSocket Approaches

Traditional HTTP Approach:
We have our old and Traditional HTTP Request-Response Stateless Approach to provide Communication between Client and Server. But it follows “Pushing” model that means when client sends a request to Server, Server pushes the response to the Clients.

WebSocket Approach:
We can use WebSocket Approach too to provide Communication between Client and Server. However unlike Traditional HTTP Request-Response Stateless Approach, WebSocket Approach provides Communication between Client and Server by using “Pulling” model that means Server always pulls data to Clients. That’s why is is more efficient and faster approach to provide Client-Server Communication.

Advantages of Socket IO(WebSocket) Programming:

  1. Faster and Two-way Communication
  2. Cross-Browser Support
  3. Cross-Platform Support
  4. Platform independent web framework

Socket IO Setup

Unlike some Node JS Default Modules like “npm”,”http”,”events” come with Node JS Platform basic installation (No need of separate steps to install these modules), Socket.IO does not come with as Node JS Default modules. We need to install it manually.

We have already discussed on “How to install a Node JS Module” using “node install” command. If you are not familiar about this command, please go through my previous post : “NPM install update and uninstall example”

To install Socket.IO globally
Before staring Express JS Development, first and fore most step We need to do is use “npm install” command to install Express JS module


npm install -g socket.io

Here “socket.io” means Socket IO Module and “-g” means install Socket.io Module globally.

To verify installation

After Socket IO Module installation is done, we need to check whether this module is installed successfully or not. If it is installed successfully, we can find a new folder at
C:\Users\[Windows_USerName]\AppData\Roaming\npm\node_modules\socket.io as shown below:

socketio_install

Socket IO Example

  • Create a Node.js:Express JS Project with default settings: “socketio” (Please refer my previous post “Express JS WebApplication with Enide Studio 2014 IDE” for more details.)
  • Update “package.json” file with “socket.io” module dependency.
  • Default package.json

    
    {
      "name": "socketio",
      "version": "0.0.0",
      "private": true,
      "scripts": {
        "start": "node ./bin/www"
      },
      "dependencies": {
        "body-parser": "~1.12.4",
        "cookie-parser": "~1.3.5",
        "debug": "~2.2.0",
        "express": "~4.12.4",
        "jade": "~1.9.2",
        "morgan": "~1.5.3",
        "serve-favicon": "~2.2.1"
      }
    }
    

    Updated package.json

    
    {
      "name": "socketio",
      "version": "0.0.0",
      "private": true,
      "scripts": {
        "start": "node ./bin/www"
      },
      "dependencies": {
        "body-parser": "~1.12.4",
        "cookie-parser": "~1.3.5",
        "debug": "~2.2.0",
        "express": "~4.12.4",
        "jade": "~1.9.2",
        "morgan": "~1.5.3",
        "serve-favicon": "~2.2.1",
        "socket.io": "~1.3.5"
      }
    }
    
  • Observe default “node_modules” folder
  • If we observe our project now, it contains all default Express JS Module libraries as shown below:

    socketio_default_node_modules

  • Update “node_modules” with “socket.io” library.
  • In order to use Socket IO module library, we need to execute the following command at our project root directory:

    
    npm install --save socket.io
    

    Here “–save” option means retrieve “socket.io” library from our Local repository and add this to our project. This is something similar to adding JAR files to our Java Project.

    Open command prompt at our project root directory and execute above command:

    socketio_npm_insatll_save_command

    NOTE:- Please ignore those errors or warnings.

    Now refresh your “socketio” project in Enide IDE Studio 2014 IDE and observe newly added socketio library to our project as shown below:

    socketio_updated_node_modules

  • Update app.js with the following content:
  • app.js

    
    // Required Modules
    var express = require('express');
    var path = require('path');
    var http = require('http');
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var io = require('socket.io');
    
    // Routings
    var index = require('./routes/index');
    var user = require('./routes/users');
    
    // Create Express App
    var app = express();
    app.set('port', process.env.PORT || 3000);
    
    //view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');
    
    
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.use('/', index);
    app.use('/users', user);
    
    var server = http.createServer(app);
    io.listen(server);
    
    io.sockets.on('connection', function (socket) {
      socket.on('messageChange', function (data) {
        console.log(data);
        socket.emit('receive', data.message.split('').reverse().join('') );
      });
    });
    
    server.listen(app.get('port'), function(){
      console.log('Express server listening on port ' + app.get('port'));
    });
    
    module.exports = app;
    

    Code Explanation

    1. Line No 1-9, importing all required dependency Node JS modules into our application
    2. Line No 12-13, importing Routings into our application
    3. Line No 16, Create Express JS Application object
    4. Line No 17, Set Express WebServer port to listen. This is how we can set our desired port number.
    5. Line No 20-21, Define our application View Template Engine i.e. JADE
    6. Line No 33, Create an HTTP Server
    7. Line No 34, Wrap HTTP Server with Socket IO(WebSocket)
    8. Line No 36-41, io.sockets.on() to open a WebSocket connection between Client and Server.
    9. Line No 47, Export our application.
  • Update index.jade file with the following content:
  • /views/index.jade

    
    extends layout
    
    block content
      h1= title
      p Welcome to 
        span.received-message #{example}
      input(type='text', class='message', onkeyup='send(this)')
      script(src="/socket.io/index.js")
      script.
        var socket = io.connect('http://localhost');
        socket.on('receive', function (message) {
          console.log('received %s', message);
          document.querySelector('.received-message').innerText = message;
        });
        function send(input) {
          console.log(input.value)
          var value = input.value;
          console.log('Sending Client Message: %s to Server', value);
          socket.emit('messageChange', {message: value});
        }
    
  • Update index.js file with the following content:
  • /routes/index.js

    
    var express = require('express');
    var router = express.Router();
    
    /* GET home page. */
    router.get('/', function(req, res, next) {
      res.render('index', { example: 'Node Express JS: Socket.IO Module',
                            title:  'Socket.IO Module' });
    });
    
    module.exports = router;
    
    
  • Final project structure looks like this:
  • ex[ress_socketio_project_structure

Execute Socket IO Example

  • Open command prompt at our project root directory and execute below command:
  • 
    npm start
    

    express_socketio_run

  • Run Socket IO Example and observe the output
  • Access application using this URL: http://localhost:3000/

    express_socketio_output1

    To see WebSocket power Internally, please use Mouse Right Click and Select “Inspect Element” as shown below:

    express_socketio_output2

    Select “Console” tab. Type some text in “Textbox” and observe the Console output as shown below:

    express_socketio_output3

    Our application sends each and every character immediately to server. That’s the beauty of WebSocket Programming.

That’s it about Express: Socket IO Module Example.

In my next post, I will give you another Socket IO Module example without using Express JS WebFramework.

Comments

  1. hitchu says:

    Excellent info here, very informative.Expecting more articles like this. Thank you. Keep the good work up.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages