3

I got that nifty App I work on, now to calculate some scenarios I'd like to know how much inbound / outbound traffic is generated per session by the app itself. I don't want to use the browser for this but to gather that info from the server side.

nodejs net.server does not have any methods that fit the description, I found only net.socket methods:

socket.bytesRead The amount of received bytes.

socket.bytesWritten The amount of bytes sent.

do they apply to the traffic generated through net.server? any existing node_modules that gather that kind of stats?

Thanks in advance

4

1 回答 1

4

Well, that's because net.server uses net.socket. To get the totals, you will have to add bytesRead and bytesWritten to the totals once the socket is closed. Example:

const net = require("net");

var server = net.createServer(function (c) {
    c.on('close', function () {
        // add to the totals
        server.bytesSent += c.bytesWritten;
        server.bytesReceived += c.bytesRead;
    });

    c.write('Hello world!\r\n');
    c.pipe(c);
    c.end();
});

server.bytesReceived = 0;
server.bytesSent = 0;

server.listen(3000);

var time = process.hrtime();
setInterval(function (){
    process.stdout.write('\u001B[2J\u001B[0;0f');
    var diff = process.hrtime(time)[0] + process.hrtime(time)[1]/1000000000;
    var bpsSent = Math.round(server.bytesSent/diff) || 0;
    var bpsReceived = Math.round(server.bytesReceived/diff) || 0;
    console.log("Running node.js %s on %s-%s", process.version, process.platform, process.arch);
    console.log("Memory usage: %d bytes", process.memoryUsage().rss);
    console.log("Uptime: %ds", Math.round(process.uptime()));
    console.log("Open connections: %d", server.connections);
    console.log("In: %d bytes (%d bytes/s)", server.bytesReceived, bpsReceived);
    console.log("Out: %d bytes (%d bytes/s)", server.bytesSent, bpsSent);
}, 100);

If you need to update the totals in real-time (when data is received/sent), you can instead add the length of the buffers directly to the totals when they are written/read. This is especially good when you have sockets that are open for a long time and transferring large amounts of data.

var server = net.createServer(function (c) {
    var oldWrite = c.write;
    c.write = function(d) {
        if (!Buffer.isBuffer(d)) {
            d = new Buffer(d);
        }
        oldWrite.call(this, d);
        server.bytesSent += d.length;
    };

    c.on('data', function(d){
        server.bytesReceived += d.length;
    });

    c.write('Hello world!\r\n');
    c.pipe(c);
    c.end();
});
于 2013-01-04T20:41:30.347 回答