Skip to content

Commit

Permalink
[major] Call the callback with an error if the server is closed
Browse files Browse the repository at this point in the history
Match the behavior of Node.js core `net.Server` and call the callback
of `WebSocketServer.prototype.close()` with an error if the server is
already closed.
  • Loading branch information
lpinca committed Jul 13, 2021
1 parent 85ca3d2 commit 09334ff
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
10 changes: 8 additions & 2 deletions lib/websocket-server.js
Expand Up @@ -145,13 +145,19 @@ class WebSocketServer extends EventEmitter {
* @public
*/
close(cb) {
if (cb) this.once('close', cb);

if (this._state === CLOSED) {
if (cb) {
this.once('close', () => {
cb(new Error('The server is not running'));
});
}

process.nextTick(emitClose, this);
return;
}

if (cb) this.once('close', cb);

if (this._state === CLOSING) return;
this._state = CLOSING;

Expand Down
14 changes: 12 additions & 2 deletions test/websocket-server.test.js
Expand Up @@ -326,11 +326,21 @@ describe('WebSocketServer', () => {
});

it("emits the 'close' event if the server is already closed", (done) => {
let callbackCalled = false;
const wss = new WebSocket.Server({ port: 0 }, () => {
wss.close(() => {
assert.strictEqual(wss._state, 2);
wss.on('close', done);
wss.close();

wss.on('close', () => {
callbackCalled = true;
});

wss.close((err) => {
assert.ok(callbackCalled);
assert.ok(err instanceof Error);
assert.strictEqual(err.message, 'The server is not running');
done();
});
});
});
});
Expand Down

0 comments on commit 09334ff

Please sign in to comment.