Skip to content

Commit

Permalink
[fix] Resume the socket in the CLOSING state
Browse files Browse the repository at this point in the history
When the value of the `readyState` attribute is `CLOSING`, the internal
socket might still be open. Resume it to read any remaining data and to
allow the connection to be closed cleanly.
  • Loading branch information
lpinca committed Nov 23, 2021
1 parent 73dec34 commit 22a26af
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,10 @@ function createWebSocketStream(ws, options) {
};

duplex._read = function () {
if (ws.readyState === ws.OPEN && !resumeOnReceiverDrain) {
if (
(ws.readyState === ws.OPEN || ws.readyState === ws.CLOSING) &&
!resumeOnReceiverDrain
) {
resumeOnReceiverDrain = true;
if (!ws._receiver._writableState.needDrain) ws._socket.resume();
}
Expand Down
26 changes: 26 additions & 0 deletions test/create-websocket-stream.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -538,5 +538,31 @@ describe('createWebSocketStream', () => {
});
});
});

it('resumes the socket if `readyState` is `CLOSING`', (done) => {
const wss = new WebSocket.Server({ port: 0 }, () => {
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
const duplex = createWebSocketStream(ws);

ws.on('message', () => {
assert.ok(ws._socket.isPaused());

duplex.on('close', () => {
wss.close(done);
});

duplex.end();

process.nextTick(() => {
assert.strictEqual(ws.readyState, WebSocket.CLOSING);
duplex.resume();
});
});
});

wss.on('connection', (ws) => {
ws.send(randomBytes(16 * 1024));
});
});
});
});

0 comments on commit 22a26af

Please sign in to comment.