Skip to content

Commit abde9cf

Browse files
committedJul 14, 2021
[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 df7de57 commit abde9cf

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed
 

‎lib/websocket-server.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -146,13 +146,19 @@ class WebSocketServer extends EventEmitter {
146146
* @public
147147
*/
148148
close(cb) {
149-
if (cb) this.once('close', cb);
150-
151149
if (this._state === CLOSED) {
150+
if (cb) {
151+
this.once('close', () => {
152+
cb(new Error('The server is not running'));
153+
});
154+
}
155+
152156
process.nextTick(emitClose, this);
153157
return;
154158
}
155159

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

‎test/websocket-server.test.js

+12-2
Original file line numberDiff line numberDiff line change
@@ -315,11 +315,21 @@ describe('WebSocketServer', () => {
315315
});
316316

317317
it("emits the 'close' event if the server is already closed", (done) => {
318+
let callbackCalled = false;
318319
const wss = new WebSocket.Server({ port: 0 }, () => {
319320
wss.close(() => {
320321
assert.strictEqual(wss._state, 2);
321-
wss.on('close', done);
322-
wss.close();
322+
323+
wss.on('close', () => {
324+
callbackCalled = true;
325+
});
326+
327+
wss.close((err) => {
328+
assert.ok(callbackCalled);
329+
assert.ok(err instanceof Error);
330+
assert.strictEqual(err.message, 'The server is not running');
331+
done();
332+
});
323333
});
324334
});
325335
});

0 commit comments

Comments
 (0)
Please sign in to comment.