Search code examples
socketsnode.jsdata-transfer

Measuring average transfer rate for data through Node.js socket


I have a regular TCP socket connection between a Node.js application (using standard net.Socket), and some other application.

Suppose I send a 1MB buffer:

socket.write(new Buffer(1048576));

While this is done in a non-blocking manner, obviously the data is not transmitted instantaneously.

How can I measure the data rate that the underlying system is sending the internal stream buffer, from my Node.js application?

Ultimately I just need to know the average speed of data being sent to the client on the other end over the last several seconds. Is this possible?


Solution

  • try to use callback in write

    var net = require('net');
    var s = net.createConnection(8888);
    s.on('connect', function() {
        function test() {
           var len = 512*1048576;
           var start = +new Date();
           var b = new Buffer(len);
           b.fill('x');
           s.write(b, function() {
               console.log(len + ' bytes written, ' + (1000*len/(+new Date() - start)).toString() + ' bytes/sec');
               test();
           });
        }
        test();
    });
    

    with nc -l 8888 > /dev/null on the other end I get around 350M bytes/sec