Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make WebSocketServer#close() emit the 'close' event #1453

Merged
merged 1 commit into from Oct 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions doc/ws.md
Expand Up @@ -101,6 +101,12 @@ to the threshold. This determines if compression is used for the entire message.
`callback` will be added as a listener for the `listening` event on the HTTP
server when not operating in "noServer" mode.

### Event: 'close'

Emitted when the server closes. This event depends on the `'close'` event of
HTTP server only when it is created internally. In all other cases, the event
is emitted independently.

### Event: 'connection'

- `socket` {WebSocket}
Expand Down
19 changes: 17 additions & 2 deletions lib/websocket-server.js
Expand Up @@ -112,6 +112,8 @@ class WebSocketServer extends EventEmitter {
* @public
*/
close (cb) {
if (cb) this.once('close', cb);

//
// Terminate all associated clients.
//
Expand All @@ -128,10 +130,13 @@ class WebSocketServer extends EventEmitter {
//
// Close the http server if it was internally created.
//
if (this.options.port != null) return server.close(cb);
if (this.options.port != null) {
server.close(() => this.emit('close'));
return;
}
}

if (cb) cb();
process.nextTick(emitClose, this);
}

/**
Expand Down Expand Up @@ -317,6 +322,16 @@ function addListeners (server, map) {
};
}

/**
* Emit a `'close'` event on an `EventEmitter`.
*
* @param {EventEmitter} server The event emitter
* @private
*/
function emitClose (server) {
server.emit('close');
}

/**
* Handle premature socket errors.
*
Expand Down
9 changes: 8 additions & 1 deletion test/websocket-server.test.js
Expand Up @@ -230,6 +230,13 @@ describe('WebSocketServer', function () {
});
});
});

it("emits the 'close' event", function (done) {
const wss = new WebSocket.Server({ noServer: true });

wss.on('close', done);
wss.close();
});
});

describe('#clients', function () {
Expand Down Expand Up @@ -689,7 +696,7 @@ describe('WebSocketServer', function () {
});
});

it('emits the `headers` event', function (done) {
it("emits the 'headers' event", function (done) {
const wss = new WebSocket.Server({ port: 0 }, () => {
const ws = new WebSocket(`ws://localhost:${wss.address().port}`);

Expand Down