detect when http client request is finished and close connection

If the request is finished before we need to respond, we set a flag and
close the connection.

We also close the connection when the request finishes anyway because we
really like a new connection for each request. Things play nicer with
bouncy that way.
This commit is contained in:
Roman Shtylman
2014-04-22 20:34:13 -04:00
parent 7fedb06bf9
commit 1b1d75b750
2 changed files with 19 additions and 1 deletions

View File

@@ -27,7 +27,8 @@
"superstack": "0.0.4", "superstack": "0.0.4",
"stylish": "0.4.1", "stylish": "0.4.1",
"makeover": "0.0.1", "makeover": "0.0.1",
"tldjs": "1.3.1" "tldjs": "1.3.1",
"finished": "1.1.2"
}, },
"devDependencies": { "devDependencies": {
"mocha": "1.18.2", "mocha": "1.18.2",

View File

@@ -9,6 +9,7 @@ var makeup = require('makeup');
var engine = require('engine.io'); var engine = require('engine.io');
var browserkthx = require('browserkthx'); var browserkthx = require('browserkthx');
var tldjs = require('tldjs'); var tldjs = require('tldjs');
var on_finished = require('finished');
var debug = require('debug')('localtunnel-server'); var debug = require('debug')('localtunnel-server');
var Proxy = require('./proxy'); var Proxy = require('./proxy');
@@ -44,11 +45,26 @@ function maybe_bounce(req, res, bounce) {
if (!client) { if (!client) {
res.statusCode = 502; res.statusCode = 502;
res.end('localtunnel error: no active client for \'' + client_id + '\''); res.end('localtunnel error: no active client for \'' + client_id + '\'');
req.connection.destroy();
return true; return true;
} }
var finished = false;
on_finished(res, function(err) {
if (err) {
return log.error(err);
}
finished = true;
req.connection.destroy();
});
// get client port // get client port
client.next_socket(function(socket, done) { client.next_socket(function(socket, done) {
// the request already finished or client disconnected
if (finished) {
return done();
}
// happens when client upstream is disconnected // happens when client upstream is disconnected
// we gracefully inform the user and kill their conn // we gracefully inform the user and kill their conn
// without this, the browser will leave some connections open // without this, the browser will leave some connections open
@@ -64,6 +80,7 @@ function maybe_bounce(req, res, bounce) {
var stream = bounce(socket, { headers: { connection: 'close' } }); var stream = bounce(socket, { headers: { connection: 'close' } });
stream.on('error', function(err) { stream.on('error', function(err) {
log.error(err);
socket.destroy(); socket.destroy();
}); });