server.closeAllConnections()
关闭连接到此服务器的所有已建立的 HTTP(S) 连接,包括连接到此服务器的正在发送请求或等待响应的活动连接。这不会破坏升级到其他协议(例如 WebSocket 或 HTTP/2)的套接字。
¥Closes all established HTTP(S) connections connected to this server, including active connections connected to this server which are sending a request or waiting for a response. This does not destroy sockets upgraded to a different protocol, such as WebSocket or HTTP/2.
这是关闭所有连接的强制方法,应谨慎使用。每当将此与
server.close
结合使用时,建议在server.close
之后调用此,以避免在对此的调用和对server.close
的调用之间创建新连接的竞争条件。¥This is a forceful way of closing all connections and should be used with caution. Whenever using this in conjunction with
server.close
, calling this afterserver.close
is recommended as to avoid race conditions where new connections are created between a call to this and a call toserver.close
.
const http = require('node:http');
const server = http.createServer({ keepAliveTimeout: 60000 }, (req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);
// Close the server after 10 seconds
setTimeout(() => {
server.close(() => {
console.log('server on port 8000 closed successfully');
});
// Closes all connections, ensuring the server closes successfully
server.closeAllConnections();
}, 10000);