Skip to content

Commit b065d92

Browse files
committed
Merge pull request #708 from minrk/close-closes
close websocket if proxyReq is closed before upgrade
2 parents f0bf741 + bcd8a56 commit b065d92

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

lib/http-proxy/passes/ws-incoming.js

+4
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,10 @@ var passes = exports;
8989
);
9090
// Error Handler
9191
proxyReq.on('error', onOutgoingError);
92+
proxyReq.on('response', function (res) {
93+
// if upgrade event isn't going to happen, close the socket
94+
if (!res.upgrade) socket.end();
95+
});
9296

9397
proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) {
9498
proxySocket.on('error', onOutgoingError);

test/lib-http-proxy-test.js

+40
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,11 @@ describe('lib/http-proxy.js', function() {
281281
client.send('hello there');
282282
});
283283

284+
client.on('error', function (err) {
285+
expect(err).to.be.an(Error);
286+
expect(err.code).to.be('ECONNRESET');
287+
});
288+
284289
proxy.on('error', function (err) {
285290
expect(err).to.be.an(Error);
286291
expect(err.code).to.be('ECONNREFUSED');
@@ -289,6 +294,41 @@ describe('lib/http-proxy.js', function() {
289294
});
290295
});
291296

297+
it('should close client socket if upstream is closed before upgrade', function (done) {
298+
var ports = { source: gen.port, proxy: gen.port };
299+
var server = http.createServer();
300+
server.on('upgrade', function (req, socket, head) {
301+
var response = [
302+
'HTTP/1.1 404 Not Found',
303+
'Content-type: text/html',
304+
'',
305+
''
306+
];
307+
socket.write(response.join('\r\n'));
308+
socket.end();
309+
});
310+
server.listen(ports.source);
311+
312+
var proxy = httpProxy.createProxyServer({
313+
// note: we don't ever listen on this port
314+
target: 'ws://127.0.0.1:' + ports.source,
315+
ws: true
316+
}),
317+
proxyServer = proxy.listen(ports.proxy),
318+
client = new ws('ws://127.0.0.1:' + ports.proxy);
319+
320+
client.on('open', function () {
321+
client.send('hello there');
322+
});
323+
324+
client.on('error', function (err) {
325+
expect(err).to.be.an(Error);
326+
expect(err.code).to.be('ECONNRESET');
327+
proxyServer.close();
328+
done();
329+
});
330+
});
331+
292332
it('should proxy a socket.io stream', function (done) {
293333
var ports = { source: gen.port, proxy: gen.port };
294334
var proxy = httpProxy.createProxyServer({

0 commit comments

Comments
 (0)