Skip to content

Instantly share code, notes, and snippets.

@glasser
Last active December 25, 2015 01:18
Show Gist options
  • Save glasser/6893545 to your computer and use it in GitHub Desktop.
Save glasser/6893545 to your computer and use it in GitHub Desktop.
Demonstrates why we need an error handler on proxySocket

To reproduce:

  • Run any websocket server. eg, 'meteor create x; cd x; meteor'. Now we have a websocket server on port 3001. (Meteor will tell you port 3000, but that's meteor's use of http-proxy; 3001 is the unproxied version.)

  • Run the above script.

  • Send lots of data through the proxy to the websocket. eg, install https://github.com/progrium/wssh and run

    yes | wssh localhost:6767/websocket

  • Kill the inner server (eg the meteor script).

Without the PR, this should crash the proxy server with an EPIPE. With the PR, it should print "HANDLED ERROR".

var http = require('http');
// Note: this uses the pre-release 1.0.0 API.
var httpProxy = require('http-proxy');
var innerPort = 3001;
var outerPort = 6767;
var proxy = httpProxy.createProxyServer({
// agent is required to handle keep-alive, and http-proxy 1.0 is a little
// buggy without it: https://github.com/nodejitsu/node-http-proxy/pull/488
agent: new http.Agent({maxSockets: 100})
});
var server = http.createServer(function (req, res) {
proxy.web(req, res, {target: 'http://127.0.0.1:' + innerPort});
});
// Proxy websocket requests using same buffering logic as for regular HTTP
// requests
server.on('upgrade', function(req, socket, head) {
proxy.ws(req, socket, head, { target: 'http://127.0.0.1:' + innerPort});
});
server.on('error', function (err) {
if (err.code == 'EADDRINUSE') {
process.stderr.write("Can't listen on port " + outerPort + "\n");
} else {
process.stderr.write(err + "\n");
}
process.exit(1);
});
proxy.ee.on('http-proxy:outgoing:web:error', function (err, req, res) {
res.writeHead(503, {
'Content-Type': 'text/plain'
});
res.end('Unexpected error.');
});
proxy.ee.on('http-proxy:outgoing:ws:error', function (err, req, socket) {
console.log("HANDLED ERROR");
socket.close();
});
server.listen(outerPort);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment