Skip to content

Commit 3c5e0af

Browse files
committed
net: handle socket.write(cb) edge case
Make sure that when calling `write()` on a connecting socket, the callback is called if the socket is destroyed before the connection is established. Fixes: #30841
1 parent 7738844 commit 3c5e0af

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

lib/net.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -886,8 +886,13 @@ Socket.prototype._writeGeneric = function(writev, data, encoding, cb) {
886886
this._pendingData = data;
887887
this._pendingEncoding = encoding;
888888
this.once('connect', function connect() {
889+
this.off('close', onClose);
889890
this._writeGeneric(writev, data, encoding, cb);
890891
});
892+
function onClose() {
893+
cb(new ERR_SOCKET_CLOSED());
894+
}
895+
this.once('close', onClose);
891896
return;
892897
}
893898
this._pendingData = null;
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const assert = require('assert');
5+
const net = require('net');
6+
7+
const server = net.createServer();
8+
server.listen(0, common.mustCall(() => {
9+
const socket = new net.Socket();
10+
11+
socket.connect({
12+
port: server.address().port,
13+
});
14+
15+
assert(socket.connecting);
16+
17+
socket.write('foo', common.expectsError({
18+
code: 'ERR_SOCKET_CLOSED',
19+
name: 'Error'
20+
}));
21+
22+
socket.destroy();
23+
server.close();
24+
}));

0 commit comments

Comments
 (0)