Skip to content

Commit

Permalink
[minor] Skip unnecessary operations if the socket is already closed
Browse files Browse the repository at this point in the history
There is no need to remove the already removed `socketOnData` listener,
resume the socket, and call `websocket.close()` if the socket is already
closed.
  • Loading branch information
lpinca committed Sep 8, 2021
1 parent 075752d commit 0e274ac
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions lib/websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -918,13 +918,15 @@ function sendAfterClose(websocket, data, cb) {
function receiverOnConclude(code, reason) {
const websocket = this[kWebSocket];

websocket._socket.removeListener('data', socketOnData);
process.nextTick(resume, websocket._socket);

websocket._closeFrameReceived = true;
websocket._closeMessage = reason;
websocket._closeCode = code;

if (websocket._socket[kWebSocket] === undefined) return;

websocket._socket.removeListener('data', socketOnData);
process.nextTick(resume, websocket._socket);

if (code === 1005) websocket.close();
else websocket.close(code, reason);
}
Expand All @@ -947,15 +949,18 @@ function receiverOnDrain() {
function receiverOnError(err) {
const websocket = this[kWebSocket];

websocket._socket.removeListener('data', socketOnData);
if (websocket._socket[kWebSocket] !== undefined) {
websocket._socket.removeListener('data', socketOnData);

//
// On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See
// https://github.com/websockets/ws/issues/1940.
//
process.nextTick(resume, websocket._socket);
//
// On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See
// https://github.com/websockets/ws/issues/1940.
//
process.nextTick(resume, websocket._socket);

websocket.close(err[kStatusCode]);
}

websocket.close(err[kStatusCode]);
websocket.emit('error', err);
}

Expand Down

0 comments on commit 0e274ac

Please sign in to comment.