Skip to content

Instantly share code, notes, and snippets.

@sergioramos
Created November 7, 2012 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergioramos/4032591 to your computer and use it in GitHub Desktop.
Save sergioramos/4032591 to your computer and use it in GitHub Desktop.

Proxying WebSockets

Websockets are handled automatically when using httpProxy.createServer(), but if you want to use it in conjunction with a stand-alone HTTP + WebSocket (such as [socket.io][5]) server here's how:

var http = require('http'),
    httpProxy = require('http-proxy');
    
//
// Create an instance of node-http-proxy
//
var proxy = new httpProxy.HttpProxy({
  target: {
    host: 'localhost',
    port: 8000
  }
});

var server = http.createServer(function (req, res) {
  //
  // Proxy normal HTTP requests
  //
  proxy.proxyRequest(req, res);
});

server.on('upgrade', function(req, socket, head) {
  //
  // Proxy websocket requests too
  //
  proxy.proxyWebSocketRequest(req, socket, head);
});

server.listen(8080);

with custom server logic

var httpProxy = require('http-proxy')

var server = httpProxy.createServer(function (req, res, proxy) {
  //
  // Put your custom server logic here
  //
  proxy.proxyRequest(req, res, {
    host: 'localhost',
    port: 9000
  });
})

server.on('upgrade', function(req, socket, head) {
  //
  // Put your custom server logic here
  //
  proxy.proxyWebSocketRequest(req, socket, head, {
    host: 'localhost',
    port: 9000
  });
});

server.listen(8080);

Configuring your Socket limits

By default, node-http-proxy will set a 100 socket limit for all host:port proxy targets. You can change this in two ways:

  1. By passing the maxSockets option to httpProxy.createServer()
  2. By calling httpProxy.setMaxSockets(n), where n is the number of sockets you with to use.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment