I have created a MEAN stack app, where on the web page these is a dashboard icon that changes colour, as it get real time updates from the back end data base. To achieve this I have used socket.io. The client side code is written below.
var socket = io();
setInterval(myfunction, 9000);
function myfunction() {
socket.on('realtime message', function (msg) {
if (msg == 'yes') { marker.setIcon({ url: imagered });}
else if (msg == 'almost') { marker.setIcon({ url: imageorange }); }
else { marker.setIcon({ url: imagegreen }); }
});
socket.emit('realtime message', 'get the temprature');
}
Every 9 sec it sends a request to the server.
var io = require('socket.io').listen(server);
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('realtime message', function (msg) {
var flag = // get the value from Mongo DB
if (flag == 'yes') {
io.emit('realtime message', 'yes');
}
else if (flag == 'almost') {
io.emit('realtime message', 'almost');
}
else { io.emit('realtime message', 'no'); }
The Mongo DB takes some time to respond back with the update value, plus the time of response getting back to client, so the request from client gets on stacking up on the server. With only one client accessing the server, the performance is good, but with 3 clients accessing the server the waiting stack becomes to large and the performance starts to drops a lot (a single get request takes 5-10 times long).
Which leaves me with the following questions to answer:
I am assuming the data is common for all clients, if that is the case, i would propose the below
Client Side
var socket = io();
socket.on('realtime message', function (msg) {
if (msg == 'yes') { marker.setIcon({ url: imagered });}
else if (msg == 'almost') { marker.setIcon({ url: imageorange }); }
else { marker.setIcon({ url: imagegreen }); }
});
Server Side
var io = require('socket.io').listen(server);
function updateClients () {
var flag = // get the value from Mongo DB
if (flag == 'yes') {
io.emit('realtime message', 'yes');
}
else if (flag == 'almost') {
io.emit('realtime message', 'almost');
}
else { io.emit('realtime message', 'no'); }
}
io.on('connection', updateClients);
setInterval(updateClients, 9000)
This basically sends the realtime messages to all clients, whenever a new client joins or every 9 seconds. In case the data is specific to clients, then you will have to handle this in a similar way