node.js TCP回复时间不一致

时间:2015-03-23 21:24:09

标签: node.js sockets tcp

我想测量从Web服务器到达响应所需的时间。我知道,对于节点,我无法获得准确的度量,但我对一致的测量非常感兴趣,所以我可以检测到我有的高滞后峰值在过去与我的托管服务提供商。

这是我为此编写的简化代码(忽略那些日志调用):

var t1, t2;
var socket = new net.Socket();

socket.on("data", function(data) {
    t2 = new Date;
    Log.w("Request time: " + (t2 - t1) + " ms");
});
socket.on("end", function() {
    Log.w("Received FIN");
});
socket.on("close", function() {
    Log.w("Socket closed");
});
socket.setNoDelay(true);

t1 = new Date;
dns.resolve4("some.host", function(err, addresses) {
    t2 = new Date;
    if (err) Log.e(err.toString());
    else {
        Log.d("DNS time: " + (t2-t1) + " ms.");
        socket.connect(80, addresses[0], function() {
            t2 = new Date;
            Log.i("Connection time: " + (t2 - t1) + " ms.");
            Log.d('Connected to ' + socket.remoteAddress);
            t1 = new Date;
            socket.write('GET / HTTP/1.1\r\nhost: some.host\r\nConnection: close\r\n\r\n', function() {
                t2 = new Date;
                Log.i("Socket writing time: " + (t2-t1) + " ms.");
                socket.end();
                t1 = new Date;
            });
        });
        t1 = new Date;
    }
});

但是,这段代码有一种奇怪的行为。当我运行它时,socket.write()data事件之间的时间出乎意料地高,超过实时的 140ms 。 但是,这是我不明白的,如果我在套接字关闭后使用相同的选项再次调用socket.connect(),或者如果我在5-15秒内重新运行脚本,我得到了正确的测量结果 这是一个输出示例:

~/node $ node test.js  
23-3-2015 22:09:19 > DNS time: 12 ms.  
23-3-2015 22:09:19 > Connection time: 23 ms.  
23-3-2015 22:09:19 > Connected to 91.142.222.187  
23-3-2015 22:09:19 > Socket writing time: 6 ms.  
23-3-2015 22:09:20 > Request time: 167 ms  
23-3-2015 22:09:20 > Received FIN  
23-3-2015 22:09:20 > Socket closed   
~/node $ node test.js  
23-3-2015 22:09:24 > DNS time: 12 ms.  
23-3-2015 22:09:25 > Connection time: 23 ms.  
23-3-2015 22:09:25 > Connected to 91.142.222.187  
23-3-2015 22:09:25 > Socket writing time: 6 ms.  
23-3-2015 22:09:25 > Request time: 23 ms  
23-3-2015 22:09:25 > Received FIN  
23-3-2015 22:09:25 > Socket closed  

这种情况发生在运行Debian的服务器以及运行Windows 8.1的计算机

我当然可以每次运行测试两次并取第二个值,但这似乎有点浪费时间,我想知道幕后发生了什么,以及如何让它工作一次性的。

提前致谢。

0 个答案:

没有答案