在两次相同的主机和端口上侦听不会触发错误

时间:2019-01-11 18:42:34

标签: javascript node.js server port

const http  = require("http");

function createServer(
  name,
  hostname
)
{
  const server = http.createServer(
    (
      request,
      response
    ) =>
    {
      console.log("request on", name);
      response.end(name);
    }
  );

  server.on(
    "error",
    (error) => console.log(`${name} error`, error)
  );

  server.on(
    "close",
    () => console.log(`${name} closed`)
  );

  server.listen(4321, hostname, () => console.log(`${name} listening (${server.listening}) on address`, server.address()));
}

createServer(
  "Server 1",
  "localhost"
);

createServer(
  "Server 2",
  "127.0.0.1"
);

createServer(
  "Server 3",
  "127.0.1.1"
);

createServer(
  "Server 4",
  "localhost"
);

createServer(
  "Server 5",
  "10.9.129.49"
);

createServer(
  "Server 6",
  "localhost"
);

使用Node v6.15.1,v8.14.1和v10.15.0,以上代码会将其打印在我的计算机上:

Server 2 listening (true) on address { address: '127.0.0.1', family: 'IPv4', port: 4321 }
Server 3 listening (true) on address { address: '127.0.1.1', family: 'IPv4', port: 4321 }
Server 5 listening (true) on address { address: '10.9.129.49', family: 'IPv4', port: 4321 }
Server 1 listening (true) on address { address: '127.0.0.1', family: 'IPv4', port: 4321 }
Server 4 listening (true) on address { address: '127.0.0.1', family: 'IPv4', port: 4321 }
Server 6 listening (true) on address { address: '127.0.0.1', family: 'IPv4', port: 4321 }

这怎么可能?我本来希望触发EADDRINUSE错误。

EDIT (此问题的先前版本)仅显示了两个使用主机名localhost的服务器。该代码已更新,以表明无论服务器数量或主机如何,问题似乎仍然存在。

更新

我尝试混合使用指向我的计算机的不同主机名(localhost127.0.0.1,本地IP等),即使打印的address对象显示了不同的值, address()没有错误。

我很好奇它是否与Node.js的server.listen方法相关,从而允许多次调用自身。也许Node.js检测到我使用的所有主机名都绑定到相同的设备和端口,所以它只是按照文档所说的那样“重新打开”。

0 个答案:

没有答案