Socket.IO excels at creating rich real-time analytic dashboards. In this recipe, we will display the count of users currently on our page, but the same concept could be used to show much more detailed analytical data if it is provided.
To show a real-time count of the users currently on a page, follow these steps:
Create a
server.js
file that emits the count of active users on the page whenever the count changes. Take a look at the following code:var express = require('express'), app = express(), http = require('http'), socketIO = require('socket.io'), server, io; app.get('/', function (req, res) { res.sendFile(__dirname + '/index.html'); }); server = http.Server(app); server.listen(5000); io = socketIO(server); var count = 0; io.on('connection', function (socket) { count++; io.emit('users.count', count); socket.on('disconnect', function () { count--; io.emit('users.count', count); }); });
Now, display...