Socket.io; easy way to handle WebSockets

WebSockets allows establishing stateful connections for bidirectional communication.

Published
Reading time3 min read

The Websites history starts with static content pages, then upgraded into dynamic, like content management system then comes ecommerce portals and lot more. Making more interactive AJAX played a huge role and all it happens thru client side request. There comes a big question what if server wants to update something in client. Multiple looping in the client side to get the update will make the performance and environment slow. To overcome this, constantly evolving web technology came up with solution to overcome this problem. It's called WebSockets.

Web sockets allows to establish the stateful connection between the client side browser and server will be exchanging the information bidirectional, which is highly benefit in application like chats, frequent reports updating, stock business, analytics and etc. Even for implementing this Websocket in applications, it is not easier as because all the browsers not follow same approach and few old will not even support this. To overcome this some libraries supports to provide cross browser management and making more durable.

Socket.io does exactly that and also provides nice API and many additional features like broadcasting. Socket.io is split into two components client and server libraries. Both written in javascript. Using Socket.io in nodejs and javascript based applications will be more advantage as it is easier for installing, importing into the application module and creating the required service.

Implementing in NodeJs Server side

Installing socket.io using npm install --save socket.io and executing the code as below similar structure:

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

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

io.on('connection', function(socket){
  socket.on('echo', function(data){
    socket.emit('echo', data);
  });
});

server.listen(8080);

Including the libraries then using Express creating the application routes and creating the socket.io instance is what derived above. After declaring libraries and routes the connection establishment with socket has to assigned and that's it from the server side.

Implementing in Client Side

Create index.html file in project's root directory and paste the following code. In client side, first thing to do is include the library and in the below example the functionality is implemented in JavaScript. Inside the code connection is created with the socket.io server by calling io() function. Next to that emitting echo event with test as a payload. Then on starting the server with nodejs server.js and connect to it by accessing the url from your browser. And on console immediately on page load will be able to see message.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Echo server</title>
    <script src="socket.io/socket.io.js"></script>
    <script type="text/javascript">
      var socket = io();
      socket.on('echo', function(data){
        console.log(data);
      });
      socket.emit('echo', 'this is a message');
    </script>
  </head>
  <body>
  </body>
</html>

I think that the most important skill for a software developer is to quickly adapt to new technologies and to always pick the right tool for the task.

Socket.io is really nice and simple. It allows us to easily consume WebSockets in any application. It's great to have it in the toolbox.