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

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

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

Real time web/versatile application are getting to be well known step by step. Administrations like Firebase and Pusher gives API’s and Services to create powerful continuous warning framework for your portable and web applications development.

We are not going to utilize these Services in this post; rather we will create application that fly up notice on specific occasion?—?Say another remark included Post. For notice we will utilize Chrome work area notice and for constant correspondence?—?Socket.io.
To begin with we make our app.js server. An extremely straightforward one.

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');
});

This server will communicate the message got from the program to every associated customer.
Our HTML page will resemble that:

<!DOCTYPE html>
<html>
    <head>
        <title>Browser Notification</title>
        <script src = "/socket.io/socket.io.js"></script>
        <script>
            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,
                });
            }
        </script>
    </head>  
    <body>
        <button type = "button" name = "button" onclick = "setNotification()">
            Send Notification
        </button>
    </body>
</html>

As should be obvious we are including the js content called socket.io/socket.io.js. This content is served by our node server.

ReactJS Routing Tutorial

Here I have a little screencast with the working illustration. As we will see there We will associate with the node server with firefox and chrome. Firefox will utilize xhr multipart and Chrome will utilize Websokets.

Actually we can utilize our node.js to serve everything (HTML, js, CSS) yet in our case we will utilize node.js for continuous stuff. Apache will serve whatever is left of the code (just a HTML document for this situation).

And that’s all. Those few lines perform the same thing than our PHP and js code in the other post’s example. Our node.js implementation is definitely smarter than the PHP one. The socket.io library also allows us to use the example with all browser. Same code and without any browser nightmare (just like jQuery when we work with DOM).

Uploading files with ReactJS and NodeJS

with Google Chrome.

Author Biography.

Lokesh Gupta
Lokesh Gupta

Overall 3+ 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.

News & Blogs

6ec3fae84857a1f5dc59eebcc6c0775e.png

Building a carousel component in React using Hooks

One of the problems in web development today is the entangling of different layers. Not only do w...

2cda7519f703462a0eabd1c2e84e0001.jpg

Why shouldn’t you wait to jump onto Angular 2?

AngularJs is a JavaScript framework and is widely adopted framework in building Single Page Web A...

8b77d9abe1f73f94ea9f0f008ff988a1.jpeg

Difference between Sets vs. Arrays in JavaScript

The Set object type was introduced in the 2015 ECMAScript specification and is ready to be used i...