DEV Community

Cover image for Stream Data to Charts in Real-Time using Websockets and Express
Manoj Mohan
Manoj Mohan

Posted on

Stream Data to Charts in Real-Time using Websockets and Express

In today's dynamic digital landscape, the demand for real-time data visualization is ever-growing. Whether it's monitoring live traffic on a website, tracking stock market fluctuations, or analyzing sensor data in IoT devices, the ability to visualize data as it streams in can provide invaluable insights and drive informed decision-making. In this blog post, we'll use Websockets and Express to stream real-time data and transform it into visually appealing charts with the help of CanvasJS.

Setting Up the Environment

First, let's set up our development environment. Make sure you have Node.js and npm installed on your system. Then, create a new directory for our project and initialize it with a package.json file:

mkdir real-time-charts-websocket-app
cd real-time-charts-websocket-app
npm init -y
Enter fullscreen mode Exit fullscreen mode

Next, install the necessary dependencies:

npm install express socket.io
Enter fullscreen mode Exit fullscreen mode

Implementing the Server

Now, let's create the server-side application using Express and integrate Websockets with socket.io

/* server.js */
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

// Serve static files from the 'public' directory
app.use(express.static('public'));

let  y = 1000;

// Handle websocket connections
io.on('connection', (socket) => {
    console.log('A client has connected');    
});

// Sending data to the server every 2 seconds
setInterval(() => {
    y += Math.round(100 + Math.random() *(-100-100));
    io.emit('data', JSON.stringify({
        value: y
    }))
}, 2000)

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

You can customize the above as per your requirement for sending data to Websocket clients e.g. broadcasting the data to a particular pool of users. Also, in the above, I am creating random data and sending it to the client on every interval. But in real-world scenario, this data can be coming from Iot devices or some third-party APIs.

Creating the Client-Side Interface

Now that we have our server set up, let's create the client-side interface where we'll display the real-time data using CanvasJS charts.

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Real-Time Charts with CanvasJS</title>
    <script src="https://cdn.canvasjs.com/canvasjs.min.js"></script>
  </head>
  <body>
    <div id="chartContainer" style="height: 300px; width: 100%"></div>

    <script src="/socket.io/socket.io.js"></script>
    <script>
      const socket = io();

      // Initialize CanvasJS chart
      const chart = new CanvasJS.Chart('chartContainer', {
        theme: 'light2',
        title: {
          text: 'Real-Time Data Visualization with Websockets',
        },
        data: [
          {
            type: 'spline',
            dataPoints: [],
          },
        ],
      });

      // Listen for incoming data
      socket.on('data', (data) => {
        data = JSON.parse(data);
        chart.options.data[0].dataPoints.push({ y: data.value });
        chart.render();
      });
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

We will be storing index.html inside public folder.

Running the Application

With both the server and client-side code in place, let's start our application by running the server:

node server.js
Enter fullscreen mode Exit fullscreen mode

Now, open your web browser and navigate to http://localhost:3000. You should see a real-time chart updating with data streamed from the server.

Conclusion

In this blog post, we've explored how to achieve real-time data visualization by streaming data with Websockets and Express, and then visualizing it using CanvasJS. By combining these powerful technologies, developers can create engaging and interactive data visualization applications that provide valuable insights to users in real time. Whether it's monitoring live analytics, tracking IoT sensor data, or visualizing financial markets, the possibilities for real-time data visualization are endless with Websockets, Express, and CanvasJS.

Top comments (1)

Collapse
 
sourovpal profile image
Sourov Pal

Hi,
This is Sourov Pal. I am a freelance web developer and Software Developer. I can do one of project for free. If you like my work you will pay me otherwise you don't need to pay. No upfront needed, no contract needed. If you want to outsource your work to me you may knock me.

My what's app no is: +8801919852044
Github Profile: github.com/sourovpal
Thanks