Skip to content

Commit

Permalink
[feature] Make WebSocketServer#close() emit the 'close' event (#1453
Browse files Browse the repository at this point in the history
)

Fixes #1375
  • Loading branch information
lpinca authored Oct 4, 2018
1 parent 6de05e0 commit 2a49c09
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
6 changes: 6 additions & 0 deletions doc/ws.md
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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

0 comments on commit 2a49c09

Please sign in to comment.