You would need a WebSocket server to make this real-time communication available.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('new message', function(msg){
io.to(msg.username).emit('new message');
});
socket.on('join', function (room) {
socket.join(room);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
In your backend, you publish a message to a specific channel, probably the channel which the user that has received a message is listening to, with a specific message e.g. "new message".
const io = require('socket.io-client');
const socket = io('localhost');
socket.emit('new message', { username: "john" });
And on the client side, the user who is getting the message is listening to this channel and will be notified.
$(function () {
var socket = io();
sio.emit('join', 'john');
socket.on('new message', function(msg){
// increment messages count
});
});