Reader small image

You're reading from  Socket.IO Cookbook

Product typeBook
Published inOct 2015
Reading LevelIntermediate
PublisherPackt
ISBN-139781785880865
Edition1st Edition
Languages
Right arrow
Author (1)
Tyson Cadenhead
Tyson Cadenhead
author image
Tyson Cadenhead

Tyson Cadenhead works as a senior JavaScript engineer at Aloompa in Nashville, Tennessee. He has dedicated his professional career to building large-scale applications in JavaScript and Node. Tyson addresses audiences at various conferences and programming meetups on how to build real-time web applications with Socket.IO or Meteor.js. He blogs on topics such as JavaScript and web technologies at http://www.tysoncadenhead.com. Tyson lives in the greater Nashville area with his wife and two sons, where he enjoys gardening, raising chickens, reading philosophy and economics books, and playing guitar.
Read more about Tyson Cadenhead

Right arrow

Real-time analytics


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.

How to do it…

To show a real-time count of the users currently on a page, follow these steps:

  1. 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);
        });
    });
  2. Now, display...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Socket.IO Cookbook
Published in: Oct 2015Publisher: PacktISBN-13: 9781785880865

Author (1)

author image
Tyson Cadenhead

Tyson Cadenhead works as a senior JavaScript engineer at Aloompa in Nashville, Tennessee. He has dedicated his professional career to building large-scale applications in JavaScript and Node. Tyson addresses audiences at various conferences and programming meetups on how to build real-time web applications with Socket.IO or Meteor.js. He blogs on topics such as JavaScript and web technologies at http://www.tysoncadenhead.com. Tyson lives in the greater Nashville area with his wife and two sons, where he enjoys gardening, raising chickens, reading philosophy and economics books, and playing guitar.
Read more about Tyson Cadenhead