Skip to content
Browse files

net: emit 'close' when socket ends before connect

Don't set `writable` to true when a socket connects if the socket is
already in an ending state.

In the existing code, afterConnect always set `writable` to true.  This
has been the case for a long time, but previous to commit
9b7a691, the socket would still be
destroyed by `destroySoon` and emit a `'close'` event. Since that
commit removed this masking behavior, we have relied on maybeDestroy to
destroy the socket when the readble state is ended, and that won't
happen if `writable` is set to true.

If the socket has `allowHalfOpen` set to true, then `destroy` will still
not be called and `'close'` will not be emitted.

PR-URL: #21290
Fixes: #21268
Reviewed-By: Luigi Pinca <>
Reviewed-By: Anna Henningsen <>
Reviewed-By: James M Snell <>
Reviewed-By: Matteo Collina <>
  • Loading branch information
Brett Kiefer authored and lpinca committed Jun 18, 2018
1 parent a13eba7 commit 64de66d78888f46c74ba8b8ea18100a9f35a1c7a
Showing with 15 additions and 1 deletion.
  1. +2 −1 lib/net.js
  2. +13 −0 test/parallel/test-net-socket-end-before-connect.js
@@ -1138,7 +1138,8 @@ function afterConnect(status, handle, req, readable, writable) {

if (status === 0) {
self.readable = readable;
self.writable = writable;
if (!self._writableState.ended)
self.writable = writable;

@@ -0,0 +1,13 @@
'use strict';

const common = require('../common');

const net = require('net');

const server = net.createServer();

server.listen(common.mustCall(() => {
const socket = net.createConnection(server.address().port);
socket.on('close', common.mustCall(() => server.close()));

0 comments on commit 64de66d

Please sign in to comment.