使用 .net 时,我注意到尝试连接到未侦听的端口总是需要 1 秒。为了检查这是否是 .net 抽象中的问题或是否是较低级别的问题,并将其与 linux 进行比较(其中不成功telnet
需要大约 3 毫秒),我使用 node.js 脚本连接到端口
- 12345,没有进程正在侦听的端口
- 80,正在监听的端口
Windows的结果:
Connecting to 127.0.0.1:12345
#3: error elapsed: 1000ms, Error: connect ECONNREFUSED
#2: error elapsed: 1002ms, Error: connect ECONNREFUSED
#4: error elapsed: 1003ms, Error: connect ECONNREFUSED
#1: error elapsed: 1007ms, Error: connect ECONNREFUSED
#0: error elapsed: 1015ms, Error: connect ECONNREFUSED
Connecting to 127.0.0.1:80
#0: connect elapsed: 8ms
#1: connect elapsed: 1ms
#2: connect elapsed: 3ms
#3: connect elapsed: 4ms
#4: connect elapsed: 6ms
Linux的结果:
Connecting to 127.0.0.1:12345
#4: error elapsed: 0ms, Error: connect ECONNREFUSED
#3: error elapsed: 1ms, Error: connect ECONNREFUSED
#2: error elapsed: 1ms, Error: connect ECONNREFUSED
#1: error elapsed: 1ms, Error: connect ECONNREFUSED
#0: error elapsed: 3ms, Error: connect ECONNREFUSED
Connecting to 127.0.0.1:80
#4: connect elapsed: 0ms
#3: connect elapsed: 0ms
#2: connect elapsed: 0ms
#1: connect elapsed: 1ms
#0: connect elapsed: 2ms
Node.js源码:
var net = require('net');
var host = process.argv[2];
var port = Number(process.argv[3]);
console.log("Connecting to %s:%d", host, port);
for (i = 0; i < 5; i++)
{
(function(i) {
var date = +new Date;
var client = net.connect({host: host, port: port});
client.on('error', function(msg)
{
console.log("#%d: error elapsed: %dms, %s", i, new Date - date, msg);
});
client.on('connect', function()
{
console.log("#%d: connect elapsed: %dms", i, new Date - date);
});
})(i);
}
一些笔记
- 我也尝试了远程 IP 地址,结果与上面显示的 localhost 类似
- 在 node.js 和我编写它的方式的情况下,(异步)连接尝试并行运行,但在 .net 的情况下,我正在同步测试,即一次又一次的尝试,结果是相同的:每次1秒
知道为什么Windows在这里很慢吗?这是某种刻意的节流吗?