Nodejs web sockets with is a library that allows simultaneous communication between client and server.

Nodejs web sockets with
socket io

Web socket is a communication protocol that allows simultaneous communication between the server and the client. Once a connection is established the connection is kept alive until either the client or the server terminates the connection. This is usually useful when creating real-time applications.

Simultaneous communication between the server and the client is not possible in regular HTTP. HTTP protocol only allows sending and receiving between the client and the server.

Unlike the HTTP protocol which utilize http:// and https:// web sockets use their own convention ws:// and wss:// respectively.

NB: Even though library utilizes web sockets it is not a replacement for web sockets. This is because adds some metadata on client and server during communication without them the connection is not usually established.

Socket.IO is a library that allows simultaneous communication between client and server using web sockets. When web sockets fail switches to HTTP long polling ensuring the data is sent regardless. In cases of complete failure does automatic re-connection.

What's HTTP long Polling

HTTP long polling keeps the HTTP connection alive until requested resources is available. After the resource is delivered the connection is terminated and the client starts another connection.  Due to the nature of http protocol (send and receive) even though long pooling is usually easy to implement it comes with latency overhead.

Web sockets offers fully duplex communication between server and client where as HTTP long polling communication is half duplex.

Diagram http long polling vs web sockets

Getting Started with Socket.IO - Chat App

We'll demonstrate by building a simple real-time chat app that utilizes using express server.

Setting up Package.json

package.json is the package management file for npm.

  • Create chat-app folder
  • Add a package.json file containing the contents below:
  "name": "chat-app",
  "version": "0.0.1",
  "description": " chat app",
  "dependencies": {}

Installing necessary dependencies

Run the following commands to install Express and

npm install express@4
Install express
npm install

Express server

Now create a file index.js

Add the below content.

const app = require('express')();
const http = require('http').Server(app);
const io = require('')(http);
const port = process.env.PORT || 3000;

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

// Socket io listening 
io.on('connection', (socket) => {
  socket.on('chat message', msg => {
    io.emit('chat message', msg);

http.listen(port, () => {
  console.log(`Socket.IO server running at http://localhost:${port}/`);

We use socket' on() to listen for socket connections. When a connection is established we listen for chat-message data upon receiving the chat-message we emit an event named chat-message using socket' emit() which can be listened on, on the client and rendered.


This is the section the user interacts with. If you take a closer look we serve it as index.html.

Create index.html file

Add below content.

<!DOCTYPE html>
    <title>Socket.IO chat</title>
      body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }

      #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
      #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
      #input:focus { outline: none; }
      #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }

      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages > li { padding: 0.5rem 1rem; }
      #messages > li:nth-child(odd) { background: #efefef; }
    <ul id="messages"></ul>
    <form id="form" action="">
      <input id="input" autocomplete="off" /><button>Send</button>
    <script src="/"></script>

      var socket = io();

      var messages = document.getElementById('messages');
      var form = document.getElementById('form');
      var input = document.getElementById('input');

      form.addEventListener('submit', function(e) {
        if (input.value) {
          socket.emit('chat message', input.value);
          input.value = '';

      socket.on('chat message', function(msg) {
        var item = document.createElement('li');
        item.textContent = msg;
        window.scrollTo(0, document.body.scrollHeight);
In the client section we have to include library on the html "<script src="/"></script> " in order for to work.

We then initialize using var socket = io(); . After initialization we can use in our script.

We add an event listener so that when the user clicks send message on the form the message is caught and emits an event chat-message  with its contents. The next block of code uses socket' on() to listen for chat-message event and append its contents to the html.


Run: node index.js

On your browser navigate to : http:\\localhost:3000  to have a look at your simple chat app.

Subscribe to Bluedoa Digest

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.