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 Aug 30, 2021
1 parent cc7a779 commit ec9377c
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions lib/websocket.js
Expand Up @@ -956,13 +956,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 @@ -985,15 +987,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 ec9377c

Please sign in to comment.