Web Socket implementation using Socket.io

We learn about web sockets and how they solve the problems caused by pooling. You can read it here if you missed it. In this article we are going to talk about the implementation of web sockets.

Web Sockets and how they solve the problem caused by pooling.

For the article I am assuming that you now a little bit about node and Javascript.

For this implementation we are going to use a node application and a well known library called as socket.io. Now look at the below server.js file

First we import express for using it. Then import http for further use and pass the express instance to it. Next we pass the http instance to socket.io and get a socket.io instance named as io.

We will use this io object to further interact with client.

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

Now that we have io instance we will make a ‘/’ route which will serve the ui for this server to be tested. The below lines send an index file which has a input field and uses jquery.

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

The content of the index file is

<!doctype html>

<html>

  <head>

    <title>Socket.IO Test application</title>



  </head>

  <body>

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

    <form action="">

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

    </form>

    <script src="/socket.io/socket.io.js"></script>

    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>

    <script>

    $(function () {

        var socket = io();

        $('form').submit(function(){

          socket.emit('io_instance', $('#m').val());

          $('#m').val('');

          return false;

        });

        socket.on('io_instance', function(msg){

          $('#messages').append($('<li>').text(msg));

        });

      });

    </script>

  </body>

</html>

It looks something like below

Web Socket implementation using Socket.io
Web Socket implementation using Socket.io

The index page is served and you can see the ui. Now look at the below code

io.on('connection', function(socket){

  console.log('a user connected');

  socket.on('io_instance', function(msg){

    console.log('message: ' + msg);

    if(msg=="hey"){

      io.emit('io_instance', "hi");

    }

    else{

    io.emit('io_instance', msg);

    }

  });

  socket.on('disconnect', function(){

    console.log('user s disconnected');

  });

});

Here whenever a new connection is made you can see in the console that a “New User Connected” message is printed. Something like below

Web Socket implementation using Socket.io
Web Socket implementation using Socket.io

When ever you type some thing in the input box you can see a message being sent to the server. Now you want to send message to the server you can send it using io.emit function like below

io.emit('io_instance', "hi");

Like in our case  I am sending the message you type in box to the client from server with a twist that whenever you type “hey” . it will send “hi”.

So who ever is connected to the server will get the message whenever anyone types anything in the input box.

Like this one below.

Web Socket implementation using Socket.io
Web Socket implementation using Socket.io

 

Now we want to verify weather it is actually solving any problem or not. We will see the network calls to verify this.

Network calls for socket.io
Network calls for socket.io

After this we send many messages and we don’t see any network calls this means it is not calling again and again and thus solving our problem.

Network calls after sending some messages
Network calls after sending some messages

 

Thus we see that there is no extra call. Below is the whole compiled code using which you can run it and see for yourself.

//Server.js file
var http = require('http').Server(application);

var io = require('socket.io')(http);

app.get('/', function(req, res){

  res.sendFile(__dirname + '/index.html');

});

io.on('connection', function(socket){

  console.log('a user connected');

  socket.on('io_instance', function(msg){

    console.log('message: ' + msg);

    if(msg=="hey"){

      io.emit('io_instance', "hi");

    }

    else{

    io.emit('io_instance', msg);

    }

  });

  socket.on('disconnect', function(){

    console.log('user disconnected');

  });

});

http.listen(3000, function(){

  console.log('listening on *:3000');

});

 

<!--- Index.html file -->
<!doctype html>

<html>

  <body>

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

    <form action="">

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

    </form>

    <script src="/socket.io/socket.io.js"></script>

    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>

    <script>

    $(function () {

        var socket = io();

        $('form').submit(function(){

          socket.emit('io_client', $('#m').val());

          $('#m').val('');

          return false;

        });

        socket.on('io_client', function(msg){

          $('#messages').append($('<li>').text(msg));

        });

      });

    </script>

  </body>

</html>

This is the end of article. If you like the article please subscribe here. 

Disclaimer: The content of the article comprises of some parts from socket.io chat tutorial you can find it here.

How to optimize javascript for performance – Top Points.


Gaurav Yadav

Gaurav is cloud infrastructure engineer and a full stack web developer and blogger. Sportsperson by heart and loves football. Scale is something he loves to work for and always keen to learn new tech. Experienced with CI/CD, distributed cloud infrastructure, build systems and lot of SRE Stuff.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.