Skip to content

Commit

Permalink
[fix] Don't emit the connection event if socket is closed prematurely
Browse files Browse the repository at this point in the history
Fixes #380
  • Loading branch information
lpinca committed Nov 16, 2016
1 parent c917a9d commit 04530ad
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/WebSocketServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ function upgrade (req, socket, head, cb) {
// allows external modification/inspection of handshake headers
this.emit('headers', headers);

if (socket.writable) {
if (socket.readable && socket.writable) {
socket.write(headers.concat('', '').join('\r\n'));
} else {
socket.destroy();
Expand Down
38 changes: 38 additions & 0 deletions test/WebSocketServer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
const assert = require('assert');
const https = require('https');
const http = require('http');
const net = require('net');
const fs = require('fs');

const WebSocket = require('..');
Expand Down Expand Up @@ -726,6 +727,43 @@ describe('WebSocketServer', function () {
});
});

it('doesn\'t emit the `connection` event if socket is closed prematurely', function (done) {
const server = http.createServer();

server.listen(++port, () => {
const wss = new WebSocketServer({
verifyClient: (o, cb) => setTimeout(cb, 100, true),
server
});

wss.on('connection', () => {
throw new Error('connection event emitted');
});

const socket = net.connect({ host: 'localhost', port }, () => {
socket.write([
'GET / HTTP/1.1',
'Host: localhost',
'Upgrade: websocket',
'Connection: Upgrade',
'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==',
'Sec-WebSocket-Version: 13',
'',
''
].join('\r\n'));
});

socket.on('end', () => {
wss.close();
server.close(done);
});

socket.setTimeout(50, () => {
socket.end();
});
});
});

it('handles messages passed along with the upgrade request (upgrade head)', function (done) {
const wss = new WebSocketServer({ port: ++port }, () => {
const req = http.request({
Expand Down

0 comments on commit 04530ad

Please sign in to comment.