Expressjs Socketio

expressjs

cometd
https://mva.microsoft.com/en-US/training-courses/building-apps-with-node-js-jump-start-8422/?l=cyMHmZKz_4304984382

How can we create an application using Express?

Express is the most popular web framework for Node, while Socket.IO is a realtime framework that enables bi-directional communication between web clients and the server. We are going to create a basic tracking pixel application using the two that has a dashboard which reports realtime visits.

Besides Express and Socket.IO we will need to install the emptygif module. When the user visits http://localhost:1337/tpx.gif, a message will be sent to all the users that are viewing the homepage. The message will contain information related to the clients, mainly their IP address and user agent.

Below is the code for the server.js file:

var emptygif = require('emptygif'); 
var express = require('express'); 
var app = express(); 
var server = require('http').createServer(app); 
var io = require('socket.io')(server); 

app.get('/tpx.gif', function(req, res, next) { 
    io.emit('visit', { 
        ip: req.ip, 
        ua: req.headers['user-agent'] 
    }); 

    emptygif.sendEmptyGif(req, res, { 
        'Content-Type': 'image/gif', 
        'Content-Length': emptygif.emptyGifBufferLength, 
        'Cache-Control': 'public, max-age=0' // or specify expiry to make sure it will call everytime 
    }); 
}); 

app.use(express.static(__dirname + '/public')); 
server.listen(1337);

Now on the frontend all we have to do is listen for that 'visit' event emitted by the server and modify the UI accordingly, like so:

<!DOCTYPE HTML> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Realtime pixel tracking dashboard</title> 
    <style type="text/css"> 
        .visit { 
            margin: 5px 0; 
            border-bottom: 1px dotted #CCC; 
            padding: 5px 0; 
        } 
        .ip { 
            margin: 0 10px; 
            border-left: 1px dotted #CCC; 
            border-right: 1px dotted #CCC; 
            padding: 0 5px; 
        } 
    </style> 
</head> 
<body> 
    <h1>Realtime pixel tracking dashboard</h1> 
    <div class="visits"></div> 

    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> 
    <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.1/moment.min.js"></script> 
    <script src="/socket.io/socket.io.js"></script> 
    <script> 
        $(function() { 
            var socket = io(); 
            var containerEl = $('.visits'); 
            socket.on('visit', function(visit) { 
                var newItem = '<div class="visit">'; 
                newItem += '<span class="date">' + moment().format('MMMM Do YYYY, HH:mm:ss') + '</span>'; 
                newItem += '<span class="ip">' + visit.ip + '</span>';
                newItem += '<span class="ua">' + visit.ua + '</span></div>'; 
                containerEl.append(newItem); 
            }); 
        }); 
    </script> 
</body> 
</html>

The polling or server-push event is achieve by the socket.on method. When the homepage is loaded, the socket.on method is invoked, which does whatever it needs to do to establish a connection with the server. When a user open a new browser window and fetch the /tpx.gif image, the server fire the 'visit' event, and the server push the event to the browser, which then execute the callback to update the browser screen.

Need to investigate this server-push events stuff. Why is it more efficient than client-poll?

Now start up the application, open the dashboard in a tab and the tracking pixel URL in different browsers. See https://www.airpair.com/javascript/node-js-tutorial

app.get(‘/‘, routes.index);

var server = http.createServer(app)
var io = require(‘socket.io’)(server);

server.listen(app.get(‘port’), function() {
}

io.on(‘connection’, function(socket) {
    mongo.connect(mongoURI, function() {
        if (err) {
            console.warn(err.message);
        } else {
            var collection = db.collection(‘chat message’);
            var stream = collection.find().sort().limit(10);
            stream.on(‘data’, function (chat) {…});
        }
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License