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 b8186dd commit ed2b803
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
Expand Up @@ -155,7 +155,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
Expand Up @@ -568,5 +568,31 @@ describe('createWebSocketStream', () => {
ws.close();
});
});

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 ed2b803

Please sign in to comment.