server.listen()


启动一个监听连接的服务器。net.Server 可以是 TCP 服务器,也可以是 IPC 服务器,这取决于它所监听的类型。

【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:】

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

【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.】

所有 listen() 方法都可以接受 backlog 参数,用于指定待处理连接队列的最大长度。实际长度将由操作系统通过 sysctl 设置(如 Linux 下的 tcp_max_syn_backlogsomaxconn)来确定。该参数的默认值为 511(不是 512)。

【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).】

所有 net.Socket 都设置为 SO_REUSEADDR(详情请参见 socket(7))。

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

server.listen() 方法只有在第一次调用 server.listen() 时发生错误或已调用 server.close() 时才能再次调用。否则,将抛出 ERR_SERVER_ALREADY_LISTEN 错误。

【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.】

在监听时最常出现的错误之一是 EADDRINUSE。当已有其他服务器正在监听请求的 port/path/handle 时,就会发生这种情况。处理这种情况的一种方法是等待一段时间后重试:

【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.error('Address in use, retrying...');
    setTimeout(() => {
      server.close();
      server.listen(PORT, HOST);
    }, 1000);
  }
});