header banner

How to Make Real Time Notification System Using Socket.io and Node.JS?

author Lokesh Gupta
Wednesday, Aug 29, 2018
2387
image

I wanted to use Socket.io and Node.JS to make a Real Time Notification system. I picked Socket.io as the library supported real-time operation with almost all the browsers. This blog helped a lot in building up the code. Socket.io used different transports for different browsers making the Real Time Notification system work across everywhere.

Real Time Notification System Using Socket.io and Node.JS

Notifications in real time has become an important aspect of Websites and Apps. As these notifications bring in more engagement, we try to make to make the code more precise and scalable.

Earlier Firebase and Pusher had been used to push real time notifications on the App and website but this time, we are planning to use Socket.io and Node.JS. Here the program will allow you to generate real-time notification in case of a specific event. The Socket.io will be using Chrome’s work area for sending notifications.

First things first. The system requires an app.js server that will be the actual communication channel. It will connect the end user to the program to receive the messages.

App.js Server Code


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

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


io.on('connection', function (socket) {
  socket.on( 'new_notification', function( data ) {
    console.log(data.title,data.message);
    io.sockets.emit( 'show_notification', { 
      title: data.title, 
      message: data.message, 
      icon: data.icon, 
    });
  });
});

http.listen(3000, function() {
   console.log('listening on localhost:3000');
});

 

HTML Code

    var socket = io();
    /**
     * Set Default Socket For Show Notification
     * @param {type} data
     * @returns {undefined}
     */
    socket.on('show_notification', function (data) {
        showDesktopNotification(data.title, data.message, data.icon);
    });
    /**
     * Set Notification Request
     * @type type
     */
    function setNotification() {
        showDesktopNotification('Lokesh', 'Desktop Notification..!', '/index.jpeg');
        sendNodeNotification('Lokesh', 'Browser Notification..!', '/index.jpeg');
    }
    /**
     * Check Browser Notification Permission
     * @type window.Notification|Window.Notification|window.webkitNotification|Window.webkitNotification|Window.mozNotification|window.mozNotification
     */
    var Notification = window.Notification || window.mozNotification || window.webkitNotification;
    Notification.requestPermission(function (permission) {
    });
    /**
     * Request Browser Notification Permission 
     * @type Arguments
     */
    function requestNotificationPermissions() {
        if (Notification.permission !== 'denied') {
            Notification.requestPermission(function (permission) {
            });
        }
    }
    /**
     * Show Desktop Notification If Notification Allow
     * @param {type} title
     * @param {type} message
     * @param {type} icon
     * @returns {undefined}
     */
    function showDesktopNotification(message, body, icon, sound, timeout) {
        if (!timeout) {
            timeout = 4000;
        }
        requestNotificationPermissions();
        var instance = new Notification(
                message, {
                    body: body,
                    icon: icon,
                    sound: sound
                }
        );
        instance.onclick = function () {
            // Something to do
        };
        instance.onerror = function () {
            // Something to do
        };
        instance.onshow = function () {
            // Something to do
        };
        instance.onclose = function () {
            // Something to do
        };
        if (sound)
        {
            instance.sound;
        }
        setTimeout(instance.close.bind(instance), timeout);
        return false;
    }
    /**
     * Send Node Notification
     * @param {type} title
     * @param {type} message
     * @param {type} icon
     * @returns {undefined}
     */
    function sendNodeNotification(title, message, icon) {
        socket.emit('new_notification', {
            message: message,
            title: title,
            icon: icon,
        });
    }

The message will be served by the node server as socket.io is being utilized. The node.js implementation is strong enough to serve notifications in real-time, it is even strong that the PHP code for real-time notification.

Practical advantage of using socket.io

  • The biggest advantage of socket.io library is that the entire set up will facilitate real-time notification on all the browsers. Utilizing the same code, the real-time messages can be send to Firefox using xhr and for Chrome Websockets will be used.
  • Reconnection of the server in case of an event that disconnects server from the notification area is handled well with socket.io. In case we are using Chrome as the work area and disconnect occurs, Application raises an event that indicates disconnect happened. Socket.io identifies the event and uses the JS code to deliver real-time notification application.
  • Node.js and socket.io needs very less code to achieve the real-time notification.

Make sure the stable version of node.js is being used and it is required to add a security layer with the node.js so that the unauthenticated users cannot use our websockets.

Other options for supporter transporters for multiple browsers in place or web sockets are: - 

  • Adobe Flash Socket
  • AJAX long polling
  • AJAX multipart streaming
  • Forever Iframe
  • JSONP Polling
author
Lokesh Gupta Overall 2+ years of experience as a Full Stack Developer with a demonstrated history of working in the information technology and services industry. I enjoy solving complex problems within budget and deadlines putting my skills on PHP, MySQL, Python, Codeigniter, Yii2, Laravel, AngularJS, ReactJS, NodeJS to best use. Through Knowledge of UML & visual modeling, application architecture design & business process modeling. Successfully delivered various projects, based on different technologies across the globe.
Older
Newer

Related Articles



blog

CRM app development for your venture - New Features Update

  In an increasingly competitive world, where the customers are more knowledgeable than ever and have plenty of options t...

blog

POS Application Development : Key Features, Time & Cost

Since several decades, businesses have been using cash registers but the arrival of digital technology, especially the internet...

blog

Magento Vs Shopify - Which e-Commerce platform is right for you

For a business planning to sell products and services online, picking the apt eCommerce platform is of utmost importance. There...

Got Something To Say

Your email address will not be published. Required fields are marked *
Name*
Email*
Website URL
Enter your comment here*

Visit Our Global Hotspots.

INDIA   |   USA

United States

1811 Fairmount Ave. 2F Philadelphia. PA 19130 USA

   +1 (215) 392-4264

United States

Wilmington,NC

   +1 (215) 392-4264

India Headquarters

401, North Avenue, Sikar Road, Jaipur (Raj)

   +1 (215) 392-4264

Or Let’s concerted our efforts!

We would be happy to answer your question. Fill out the query form & we’ll be in touch as soon as possible.

Name
Email ADDRESS
Phone number
SKYPE
MESSAGE
roll

Let’s Talk Business
Feel Free to contact with us

Forget about the stock proposals. Your business is unique, and so we provide unique solutions and pricing.

Our Clients Simply Love Our Work

Your full name
Your email address
Your phone number
Your budget
How can we help you ?

Get in touchwith us

The speed and quality of the work Xtreem Solution provided really impressed me.Highly recommeded

Darren G.

Stock Bag Retailer