Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions lib/net.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const {
NumberParseInt,
ObjectDefineProperty,
ObjectSetPrototypeOf,
SafeSet,
Symbol,
SymbolAsyncDispose,
SymbolDispose,
Expand Down Expand Up @@ -912,6 +913,7 @@ Socket.prototype._destroy = function(exception, cb) {
if (this._server) {
debug('has server');
this._server._connections--;
this._server._connectionSockets?.delete(this);
if (this._server._emitCloseIfDrained) {
this._server._emitCloseIfDrained();
}
Expand Down Expand Up @@ -1867,6 +1869,7 @@ function Server(options, connectionListener) {
}

this._connections = 0;
this._connectionSockets = new SafeSet();

this[async_id_symbol] = -1;
this._handle = null;
Expand Down Expand Up @@ -2365,6 +2368,7 @@ function onconnection(err, clientHandle) {
}

self._connections++;
self._connectionSockets.add(socket);
socket.server = self;
socket._server = self;
self.emit('connection', socket);
Expand Down Expand Up @@ -2436,6 +2440,22 @@ Server.prototype.close = function(cb) {
this._handle = null;
}

// Register a beforeExit handler to destroy any remaining connections
// before the process exits. This ensures connections are torn down
// during normal JS execution rather than during environment cleanup,
// where on Windows the IOCP completion processing can race with
// handle teardown.
if (this._connectionSockets.size > 0) {
const connections = this._connectionSockets;
const onBeforeExit = () => {
process.removeListener('beforeExit', onBeforeExit);
for (const socket of connections) {
socket.destroy();
}
};
process.on('beforeExit', onBeforeExit);
}

if (this._usingWorkers) {
let left = this._workers.length;
const onWorkerClose = () => {
Expand Down
Loading