server.listen()


为 connections 启动一个 server 监听. 一个 net.Server 可以是一个 TCP 或者 一个 IPC server,这取决于它监听什么。

可能的参数:

这个函数是异步的。当 server 开始监听,'listening' 事件会触发。最后一个参数 callback 将会被添加为'listening' 事件的监听器。

所有的 listen() 方法可以传入一个 backlog 参数来指定待连接队列的最大长度。 实际长度将通过 OS 的 sysctl 设置, 例如 linux 里的 tcp_max_syn_backlogsomaxconn。 这个参数的默认值是511 (不是512)

说明

  • 所有的 net.Socket 都被设置为 SO_REUSEADDR (详见 [socket(7)][])

  • server.listen() 方法可能会被调用多次。每个后续的调用都将使用其提供的选项重新打开服务器。

监听时,其中一个最常见的错误是 EADDRINUSE。这是因为另一个 server 已经监听了该请求中的 port / path / handle。 处理这种情况的一种方法是在一定时间后重试:

server.on('error', (e) => {
  if (e.code === 'EADDRINUSE') {
    console.log('Address in use, retrying...');
    setTimeout(() => {
      server.close();
      server.listen(PORT, HOST);
    }, 1000);
  }
});

Start a server listening for connections. A net.Server can be a TCP or an IPC server depending on what it listens to.

Possible signatures:

This function is asynchronous. When the server starts listening, the 'listening' event will be emitted. The last parameter callback will be added as a listener for the 'listening' event.

All listen() methods can take a backlog parameter to specify the maximum length of the queue of pending connections. The actual length will be determined by the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on Linux. The default value of this parameter is 511 (not 512).

All net.Socket are set to SO_REUSEADDR (see socket(7) for details).

The server.listen() method can be called again if and only if there was an error during the first server.listen() call or server.close() has been called. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

One of the most common errors raised when listening is EADDRINUSE. This happens when another server is already listening on the requested port/path/handle. One way to handle this would be to retry after a certain amount of time:

server.on('error', (e) => {
  if (e.code === 'EADDRINUSE') {
    console.log('Address in use, retrying...');
    setTimeout(() => {
      server.close();
      server.listen(PORT, HOST);
    }, 1000);
  }
});