Skip to content

Commit 09334ff

Browse files
committed
[major] Call the callback with an error if the server is closed
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.
1 parent 85ca3d2 commit 09334ff

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

lib/websocket-server.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,13 +145,19 @@ class WebSocketServer extends EventEmitter {
145145
* @public
146146
*/
147147
close(cb) {
148-
if (cb) this.once('close', cb);
149-
150148
if (this._state === CLOSED) {
149+
if (cb) {
150+
this.once('close', () => {
151+
cb(new Error('The server is not running'));
152+
});
153+
}
154+
151155
process.nextTick(emitClose, this);
152156
return;
153157
}
154158

159+
if (cb) this.once('close', cb);
160+
155161
if (this._state === CLOSING) return;
156162
this._state = CLOSING;
157163

test/websocket-server.test.js

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -326,11 +326,21 @@ describe('WebSocketServer', () => {
326326
});
327327

328328
it("emits the 'close' event if the server is already closed", (done) => {
329+
let callbackCalled = false;
329330
const wss = new WebSocket.Server({ port: 0 }, () => {
330331
wss.close(() => {
331332
assert.strictEqual(wss._state, 2);
332-
wss.on('close', done);
333-
wss.close();
333+
334+
wss.on('close', () => {
335+
callbackCalled = true;
336+
});
337+
338+
wss.close((err) => {
339+
assert.ok(callbackCalled);
340+
assert.ok(err instanceof Error);
341+
assert.strictEqual(err.message, 'The server is not running');
342+
done();
343+
});
334344
});
335345
});
336346
});

0 commit comments

Comments
 (0)