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.

Also Read:-How to Deploy a Simple HTML/CSS/Javascript Application on Heroku

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

Learn Internet Of Things by CrowdforGeeks

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>

Learn Socket IO Programming With CrowdforGeeks

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 Internet Of Things by CrowdforGeeks

How to Develop a Blog App Using NextJS



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.

Join Our Newsletter.

Subscribe to CrowdforThink newsletter to get daily update directly deliver into your inbox.

CrowdforJobs is an advanced hiring platform based on artificial intelligence, enabling recruiters to hire top talent effortlessly.

CrowdforJobs

CrowdforApps brings to you the well researched list of the most successful and finest App development companies, Web software developers.

CrowdforApps

CrowdforGeeks is where lifelong learners come to learn the skills they need, to land the jobs they want, to build the lives they deserve.

CrowdforGeeks

CrowdforThink is a leading Indian media and information platform, known for its end-to-end coverage of the Indian startup ecosystem.

CrowdforThink
CFT

News & Blogs

449d4afbbedaaf5c3f17ee0d225c7edb.png

A Simple CRUD App Using GraphQL, NodeJS, and Mo...

In my last article, I gave a global introduction to GraphQL. I compared it with REST, as the two ...

5ff4ac229fb322d3b10b879f82f86616.png

Top 8 Reasons To Learn NodeJS In 2020

 Javascript is the most well-known programming language utilized in numerous new companies a...

b05f3543218e314a9b8bcee5390054b9.png

How to Install Node.js and NPM on Windows 10

Stage 1: Download Node.js Installer  In an internet browser, explore to https://nodejs.org/...

Top Authors

Hey, I am Suraj - a full-time blogger and a social media expert currently working on the Growth H...

Suraj Kumar

With good communication and writing skiils, Astha Sharma is a full-time content writer working wi...

Astha Sharma

Overall 3+ years of experience as a Full Stack Developer with a demonstrated history of working i...

Lokesh Gupta

Aditya Sehgal is a recognised financial adviser, tech and gadget writer and blogger. Still he has...

Aditya Sehgal
CFT

Our Client Says

WhatsApp Chat with Our Support Team