Welcome to another PieSocket tutorial, today we are going to build a live chart using WebSockets in Javascript.
A backend script is needed for this and we will use NodeJS, you can use almost any programming language for the backend and the process remains almost the same.
We will use PieSocket Channels – a managed WebSocket SDK, which makes it easy to build and scale realtime applications. If you choose to use some other programming language than Node for the backend, for example PHP. Have a look at PieSocket Docs, and replace the backend code for publishing the graph data.
Lets begin by creating an empty direcotory
1 2 |
mkdir realtime-charts cd realtime-charts |
Create another directory inside it, lets call it public.
1 |
mkdir public |
Create a file, index.html inside public directory. This will be the file where we place our Javascript code for frontend.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Realtime Graph</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script src="https://unpkg.com/piesocket-js@2"></script> </head> <body> </body> </html> |
Look into the head section of index.html, notice we have included two JavaScript libraries, ChartJS and PieSocketJS.
ChartJS
ChartJS is a beautiful graphing library for JavaScript. It can be used with ReactJS, VueJS, AngularJS and almost any Javascript frontend library to create beautiful realtime graphs.
PieSocketJS
PieSocketJS is client-side SDK provided by PieSocket, it is used to build serverless realtime applications.
We can now proceed to add a static chart into our frontend file. Add the following code snippet into body of the index.html file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<div style="width:500px;margin:10px;"> <h2>Realtime Graph</h2> <canvas id="myChart"></canvas> </div> <script> const ctx = document.getElementById('myChart'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], 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: { scales: { y: { beginAtZero: true } } } }); </script> |
This will add a static chart to our frontend. No worries if the configurations in the script do not make sense, you can refer to ChartJS docs later and figure them out as needed. For now just copy and paste the give code.
To check the results of the html file and see how the frontend looks, you can open it within a browser by right clicking on it.
We finish the frontend part of the code by adding following code snippet into the script tag of the index.html file.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var piesocket = new PieSocket({ clusterId: 'demo', apiKey: 'oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm' }); piesocket.subscribe("piesocket-realtime-chart").then(channel => { console.log("PieSocket connnected"); channel.listen('chart-data', function (data, meta) { myChart.data.datasets[0].data = data; myChart.update(); }); }) |
There are two parts in the code we pasted above. The first part initialises PieSocket javascript client library with a demo API key, taken from this websocket tester. You should replace the API key with your own API key from PieSocket.
Next part of the code subscribes to a Channel “piesocket-realtime-chart” and once the subscription in ready, it registers a callback which will be triggered everytime an event named “chart-data” is published from the backend. This is where we update the chart.
With this our frontend code is ready and we can proceed to create the backend code which will publish updated chart data every second to make our chart dynamic.
Initialise node into the directory realtime-charts by running
1 |
npm init |
Complete the prompt that follow and once its done, install following dependencies.
1 |
npm i express piesocket-nodejs |
Express is a lightweight node web-server. PieSocket-NodeJS is the server-side SDK for PieSocket Channels.
We have installed all we need, its time to write the backend code. Create a file server.js into the same directory and add following code to it.
1 2 3 4 5 6 |
const express = require('express'); const app = express(); app.use(express.static(__dirname + '/public')); app.listen('3000'); console.log('Server running on: http://localhost:3000'); |
This creates a express web-server which will run on port 3000 and server static files from the public directory we created earlier.
Include PieSocket-NodeJS into your project by adding the following at the very top of server.js
1 2 3 4 5 6 7 |
const PieSocket = require("piesocket-nodejs"); const piesocket = new PieSocket({ clusterId: 'demo', apiKey: 'oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm', secret: 'd8129f82f8dd71910aa4a7efa30a7297' }); |
Remember to replace the demo API key and secret with your own.
Next, we will add the code responsible for publishing chart-data every second to the frontend.
Add the following code to the bottom of server.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function getRandomNumber(min, max){ var random = Math.floor(Math.random() * (max - min + 1)) + min; return random; } setInterval(function(){ console.log("Sending new graph data"); piesocket.publish("piesocket-realtime-chart", "chart-data" , [ getRandomNumber(1, 10), getRandomNumber(1, 10), getRandomNumber(1, 10), getRandomNumber(1, 10), getRandomNumber(1, 10), getRandomNumber(1, 10) ]); }, 1000); |
The complete server.js file should look like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
const PieSocket = require("piesocket-nodejs"); const piesocket = new PieSocket({ clusterId: 'demo', apiKey: 'oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm', secret: 'd8129f82f8dd71910aa4a7efa30a7297' }); const express = require('express'); const app = express(); app.use(express.static(__dirname + '/public')); app.listen('3000'); console.log('Server running on: http://localhost:3000'); function getRandomNumber(min, max){ var random = Math.floor(Math.random() * (max - min + 1)) + min; return random; } setInterval(function(){ console.log("Sending new graph data"); piesocket.publish("piesocket-realtime-chart", "chart-data" , [ getRandomNumber(1, 10), getRandomNumber(1, 10), getRandomNumber(1, 10), getRandomNumber(1, 10), getRandomNumber(1, 10), getRandomNumber(1, 10) ]); }, 1000); |
Run the server.js code
1 |
node server.js |
Open http://localhost:3000/ in your browser and you should see a beautiful, magical realtime graph dancing for you. You can change the type of chart, add whatever data you would like to it. See ChartJS documentation to learn more about how to customise your chart.
This project is available on Github: https://github.com/piesocket/realtime-charts-javascript
Thanks for reading, hope it helps, leave a comment if you liked this tutorial.