34

Real-time Data Visualization with Socket.io and jQuery

 4 years ago
source link: https://www.telerik.com/blogs/real-time-data-visualization-with-socket.io-and-jquery
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Real-time is about sending and updating data as fast as possible in an automated, synchronous and bi-directional manner. It communicates between endpoints and updates data at a speed almost unnoticeable by the user. In summary, a change on one end will trigger a near-instant change on another end.

In today’s world, various data gets updated almost every second due to many factors and the only way to make sense of it is to have a visual representation. Stock market, cryptocurrencies, social networks, flight data, etc. are various examples of such data.

Prerequisites

To follow this tutorial, a basic understanding of jQuery and Node.js is required. Also ensure that you have at least Node version 8+ installed on your development machine before you begin. HTML/CSS knowledge is also recommended but not mandatory.

To build the required application, here are a few tools we’ll use:

E3iiUv2.png!web

Initializing the Application

Building a chart dashboard application with HTML, CSS and jQuery is possible; however, to add real-time collaborative features, we need a server to act as the middleman between all the connected clients (browsers).

We will use Node because we can easily create a minimal server with Express. We will be using a very minimal setup for this project. Create a folder called realtime and create a package.json file inside it. Now, add the following code:

// ./package.json
	{
		"name": "realtimeproject",
		"version": "1.0.0",
		"description": "Real time app"
		"main": "app.js",
		"scripts": {
		"test": "echo \"Error: no test specified\" && exit 1",
		"start": "node app"
		},
		"author": "",
		"license": "ISC",
		"dependencies": {
		"express": "^4.16.4",
		"pubnub": "^4.22.0",
		"socket.io": "^2.2.0"
		}
	}

Now when you run npm Install it runs the script and installs all our dependencies. If it ran properly you should now see a node_modules folder and a package-lock.json file. Now that this is out of the way, let’s go ahead and start writing some code.

In the root directory create an app.js file. This file will be the entry point of our application. Then create a public folder where we will store our html file and static assets. Inside it, create an index.html file and a js directory and initialize a charts.js file in the directory.

Right now our folder structure should look like this:

realtime/
    node_modules/
    public/
        js/
         charts.js
        index.html
    app.js
    package.json
    package-lock.json

Open the app.js file and add the following code to it:

// ./app.js 
    
    const express = require('express')
    const app = express()
    const PubNub = require('pubnub');
    
    //middlewares
    app.use(express.static('public'))
    
    
    //Listen on port 3000
    server = app.listen(3000);
    
    const io = require("socket.io")(server)

Here, we require Express and initialize it. We then go ahead and use it to serve the files in our public folder. Now whenever you type npm start in the terminal, the files in the public folder get served as your homepage. That’s it for our basic server with Express. Now let’s go ahead and create our real-time application. We will revisit this file when we are ready to add real-time features.

Creating the Dashboard with Chart.js

Open your index.html file in the public folder and add the following lines of code:

<!-- /public/index.html -->
    
    <!DOCTYPE html>
    <html lang="en">
          <head>
              <meta charset="utf-8">
              <title>RealTime Dashboard</title>
              <!-- Bootstrap CSS File -->
              <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
              <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js">           </script>
           </head>
            <body>
           <div class="container">
              <canvas id="myChart"></canvas>
           </div>
           
          <script src="https://code.jquery.com/jquery-3.3.1.js"
           integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
           crossorigin="anonymous">
          </script>
    
          <script src="js/charts.js"></script>
       </body> 
    </html>

Here we import Bootstrap and ChartJs through a CDN. In the body of our file, we define an area where the chart will be placed. Finally, at the end of our file we import jQuery and include our charts.js file.

Now it’s time to write the function for creating the chart. We will do that in the charts.js file. Open it up and add the following lines of code to it:

// public/js/charts.js
    
    function init () {
     let ctx = document.getElementById("myChart").getContext("2d");
     let myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: [],
            datasets: [{
                label: 'Google',
                data: [],
                backgroundColor: [
                    'rgba(255, 99, 132, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(75, 192, 192, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                    'rgba(255, 159, 64, 0.2)'
                ],
                borderColor: [
                    'rgba(255, 99, 132, 1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }]
                },
                options: {}
            });
       }
    }
           
    $(init);

In this file we create a wrapper function (init) where we will write our methods for our charts. We first select the canvas where we want the chart to be placed. Then we initialize the chart function to it along with some of its properties to handle the type, different colors, labels and data that will control our chart. We initially set the data to an empty array (we will update this data dynamically). Finally, we initialize the function using jQuery’s $ utility.

Now if you run npm start from your terminal you should see this empty chart.

MjyIJn2.png!web

N/B: All the files in this tutorial can be found in this repo .

Going Real-time with Socket.io

Right now, we have a working application. Next, we need to make it real-time using Socket.io . We already installed Socket.io as one of our node dependencies, so all we need to do is initialize it in our app.js . Open up the file and add the following code to it:

// ./app.js
    
    //socket.io instantiation
    const io = require("socket.io")(server)
    
    //listen on every connection
    io.on('connection', function (socket) {
    
            //Instantiate a new Pubnub instance along with the subscribeKey 
             pubnub = new PubNub({
                    subscribeKey : 'sub-c-4377ab04-f100-11e3-bffd-02ee2ddab7fe'
                })
    
        //adding listener to pubnub
         pubnub.addListener({
            message: function(message) {
      /*checking whether the message contains data for the ‘Apple’ category or not.*/
              if(message.message.symbol=='Google'){
                     /*Create a new date object from the specified message.timestamp.*/ 
                      let x = new Date(message.message.timestamp);
                     //Converting the timestamp into a desired format. HH:MM:SS:MS
                     let time =  (x.getHours()) + ':' + (x.getMinutes()) + ':' + (x.getSeconds()) + ':' + (x.getMilliseconds());
              /*Here we are creating an object which will contain a timestamp as label and the ‘order_quantity’ as value.*/
                    let data = {"label": time, "value":message.message.order_quantity}
                   //sending data to the client
                    socket.broadcast.emit('updateChart', data);
                    }; 
            }
        })      
        
        //Subscribe the PubNub channel
        pubnub.subscribe({
            channels: ['pubnub-market-orders'] 
        });
    });

Now we have initialized Socket.io in our app on the server. On every connection to that instance we initialize our connection to PubNub and give it the subscribe key to the artificial data channel. We add an event listener to grab Google’s data from the channel, convert it to our desired format then finally emit it to the client. Finally, we subscribe to the channel.

We need to add code to the client side to make it connect to the socket instance on the server and receive data from it. Open the index.html file and add the following code before the end of the body tag.

// /public/index.html
    
    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io('http://localhost');
      socket.on('connect', function(){});
      socket.on('event', function(data){});
      socket.on('disconnect', function(){});
    </script>

Now update your chart.js file and add the following lines of code in bold:

// public/js/chart.js
    let socket;
    
    function init () {
    
     socket = io.connect("http://localhost:3000");
           //other code stays same
     socket.on('updateChart', (data) => {
           addData(myChart, data.label, data.value);
     });
    }
    
    
    function addData(chart, label, data) {
        chart.data.labels.push(label);
        chart.data.datasets.forEach((dataset) => {
            dataset.data.push(data);
        });
        chart.update();
    }
           
    $(init);

Here we connect to the socket instance on the server and update our chart data by calling the addData function and passing the relevant data to it to build our display.

Now start your application by typing npm start under the project directory in your terminal. Open up http://localhost:3000 and you will see the chart update in real time.

RZZ7Vzv.png!web

s_703FF9C41C9BEE042EA7B290F4D588C4F4241AE156185F5959BDE8CFF812A9A1_1552751223469_2.png

Conclusion

In this tutorial we learned how to use jQuery, Node.js, HTML and CSS to build a real-time chart application. The knowledge from here can help you create more complex real-time apps. Be sure to check out the Socket.io docs and post comments for clarity on parts you don’t understand. Happy coding.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK