YouTube Icon

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

Also Read:- Uploading files with ReactJS and NodeJS

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.

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

Our mission is "Har Koi Dekhe Video, Har Ghar Dekhe Video, Ghar Ghar Dekhe Video" so we Provide videos related to Tutorials, Travel, Technology, Wedding, Cooking, Dance, Festivals, Celebration.

Apna Video Wala
CFT

News & Blogs

41aa280eef897eb68aed34341b0f5425.png

Best Node.js Frameworks for App Development in ...

Node.js has made quite a name for itself in the last few years. The increasing demand for web app...

db3dea5fd7cf69805e438fb629ed4977.png

What Makes the Best Website Homepage Design? Co...

Page layout design can assist you in determining not only which material to utilize and where to ...

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

Top Authors

Lamia Rochdi is the Marketing Manager at Bell Flavors & Fragrances EMEA. A successful family-...

Lamia Rochdi

I’m Mertin Wilson a technician in a camera company and certified expert of different P...

Mertin Wilson

Zakariya has recently joined the PakWheels team as a Content Marketing Executive, shortly after g...

Zakariya Usman

Pankaj Singh is a Senior Digital Marketing Consultant with more than 2 years of experience in SEO...

Pankaj Singh
CFT

Our Client Says

WhatsApp Chat with Our Support Team