Sitemap

Utilising Socket.IO For Real Time Data Visualisation using Node.js.

3 min readNov 29, 2022

When representing real time data on a webpage, a common problem is that http request require refreshing the page using polling. This is bad for performance and overall user experience. Leading to slow response times and heavy work loads server side.

To rectify this problem we need to create a real time connection, Often referred to as a full-duplex connection. Allowing for both the server and the client to constantly listen for asynchronous messages being send between each other without the need to refresh the page.

Creating a Simple Server-side Implementation with Web Sockets

const WebSocket = require('ws')
const server = new WebSocket.Server({ port: '8080' })
var clients = [];

server.on('connection', async (socket) => {
console.log("Socket Opened");
clients.push(socket);
socket.on('message', async (message) => {

var incomingData = JSON.parse(message)
var data =
{
TimeStamp: Date.now(),
Label: incomingData.Label,
Data: parseInt(incomingData.Data)
}
console.log(data);
clients.forEach(function(client) {
client.send(JSON.stringify(data));
});
});
socket.onclose = event => {
console.log(event.reason);
const index = array.indexOf(socket);
if (index > -1) { // only splice array when item is found
array.splice(index, 1); // 2nd parameter means remove one item only
}

};

});

As you can see to be able to send synced data over standard web sockets means you need to iterate over each client currently connected, which can start to get complicated as your application grows larger. We can do this much more simply with Socket.io

What is Socket.IO?

Socket.IO is a library that solves common issues that occur with web sockets like the issue of broadcasting messages to multiple clients at once. It also has failovers that allow for inbuilt handling of issues such as connection drops.

Adding Socket.IO to our Server-side Implementation

const app = require('express')();
const http = require('http').Server(app);

const io = require('socket.io')(http, {
cors: { origin: "*" }
});

io.on('connection', (socket) => {
console.log('a user connected');

socket.on('message', (message) => {
console.log(message);
var incomingData = JSON.parse(message)
var data =
{
TimeStamp: Date.now(),
Label: incomingData.Label,
Data: parseInt(incomingData.Data)
}

io.emit('message', JSON.stringify(data) );
});
});

http.listen(8080, () => console.log('listening on http://localhost:8080') );

The code above no longer need to keep an index of each client that is connected to the system as it it now able to broadcast messages with event names without the need for individual messages such as with the web socket implementation.

Implement Socket.IO to the Client Side Implementation

Implementing Socket.io is easy all you need to do is add the relevant client side script.

    <script src="https://cdn.socket.io/socket.io-3.0.0.js"></script>

From there we can utilise the emit function within Socket.io that tells the server that a message is to be broadcasted across the whole network under a network event name.

document.getElementById('send').onclick = () => {
console.log("Sending Data");
const Label = document.getElementById('label').value;
const Data = document.getElementById('data').value;
var data =
{
TimeStamp: Date.now(),
Label: Label,
Data: Data
}
socket.emit('message',JSON.stringify(data));

For this example the network event name was “message”. This means the server is listening for an event to occur under this name allowing for the data to be filter from other network events occurring on the network.

socket.on('message', data => {
var incomingData = JSON.parse(data)


console.log('Data from server ', data);
chart.data.labels.push(String(incomingData.Label))
chart.data.datasets.forEach((dataset) => {
dataset.data.push(incomingData.Data);
});
chart.update();
});

This is then listened to on all clients so that they can receive the data asynchronously allowing for real time updating of data across a host of client without the need to index each client individually.

--

--

Jack Bonnell
Jack Bonnell

Written by Jack Bonnell

0 followers

Senior CoreTech Engineer

No responses yet