diff --git a/lib/net.js b/lib/net.js index 4b3b96c8cd2736..6c523fcd214708 100644 --- a/lib/net.js +++ b/lib/net.js @@ -631,10 +631,20 @@ Socket.prototype.destroySoon = function() { if (this.writable) this.end(); - if (this.writableFinished) + if (this.writableFinished && this.readableEnded) this.destroy(); else - this.once('finish', this.destroy); + this.once('finish', () => { + // If we destroy the socket before we have received an incoming EOF + // the remote might still be sending data that will trigger a RST + // from this host once it is received + // Closing a TCP socket requires two FIN/ACK exchanges, one in every + // direction - this means two events + if (this.readableEnded) + this.destroy(); + else + this.once('end', this.destroy); + }); }; diff --git a/test/parallel/test-http-should-keep-alive.js b/test/parallel/test-http-should-keep-alive.js index 038af47ee4db97..33fa46187040d6 100644 --- a/test/parallel/test-http-should-keep-alive.js +++ b/test/parallel/test-http-should-keep-alive.js @@ -49,7 +49,7 @@ const countdown = new Countdown(SHOULD_KEEP_ALIVE.length, () => server.close()); const getCountdownIndex = () => SERVER_RESPONSES.length - countdown.remaining; const server = net.createServer(function(socket) { - socket.write(SERVER_RESPONSES[getCountdownIndex()]); + socket.end(SERVER_RESPONSES[getCountdownIndex()]); }).listen(0, function() { function makeRequest() { const req = http.get({ port: server.address().port }, function(res) {