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).

Future Of Node.JS And Why You Should Learn Node.Js In 2020

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

Learn Ajax With CrowdforJobs


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

04dd32c0108d23bf51249aeab490ad84.png

Get a head start with trending Nodejs developer...

To build and run applications, you need different types of runtime environments that help in seve...

99c65279a4f62ad85fb5b8b340077bb3.png

How to Integrate Payumoney Payment Gateway in L...

I am going to explain How to Integrate Payumoney Payment Gateway in Laravel 5. Most of thing are ...

045b052a4c56e8680d2177403a62bb23.png

Important Things You Need To Know About Agile D...

In 2001, a gathering of 17 programming engineers met and talked about another way of thinking in ...