Skip to content

Commit

Permalink
[fix] Make WebSocket#close() work when called from a headers listener
Browse files Browse the repository at this point in the history
  • Loading branch information
lpinca committed Apr 20, 2017
1 parent 309d77f commit 3633d6c
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/WebSocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -653,10 +653,16 @@ function initAsClient (address, protocols, options) {
});

this._req.on('upgrade', (res, socket, head) => {
this._req = null;

this.emit('headers', res.headers, res);

//
// The user may have closed the connection from a listener of the `headers`
// event.
//
if (this.readyState !== WebSocket.CONNECTING) return;

this._req = null;

const digest = crypto.createHash('sha1')
.update(key + constants.GUID, 'binary')
.digest('base64');
Expand Down
28 changes: 28 additions & 0 deletions test/WebSocket.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -999,6 +999,20 @@ describe('WebSocket', function () {
});
});

it('can be called from a listener of the headers event', function (done) {
const wss = new WebSocketServer({ port: ++port }, () => {
const ws = new WebSocket(`ws://localhost:${port}`);

ws.on('open', () => assert.fail(null, null, 'connect shouldnt be raised here'));
ws.on('error', (err) => {
assert.ok(err instanceof Error);
assert.strictEqual(err.message, 'closed before the connection is established');
ws.on('close', () => wss.close(done));
});
ws.on('headers', () => ws.close());
});
});

it('throws an error if the first argument is invalid (1/2)', function (done) {
const wss = new WebSocketServer({ port: ++port }, () => {
const ws = new WebSocket(`ws://localhost:${port}`);
Expand Down Expand Up @@ -1209,6 +1223,20 @@ describe('WebSocket', function () {
});
});

it('can be called from a listener of the headers event', function (done) {
const wss = new WebSocketServer({ port: ++port }, () => {
const ws = new WebSocket(`ws://localhost:${port}`);

ws.on('open', () => assert.fail(null, null, 'connect shouldnt be raised here'));
ws.on('error', (err) => {
assert.ok(err instanceof Error);
assert.strictEqual(err.message, 'closed before the connection is established');
ws.on('close', () => wss.close(done));
});
ws.on('headers', () => ws.terminate());
});
});

it('does nothing if the connection is already CLOSED', function (done) {
const wss = new WebSocketServer({ port: ++port }, () => {
const ws = new WebSocket(`ws://localhost:${port}`);
Expand Down

0 comments on commit 3633d6c

Please sign in to comment.