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);
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);
By default, node-http-proxy
will set a 100 socket limit for all host:port
proxy targets. You can change this in two ways:
- By passing the
maxSockets
option tohttpProxy.createServer()
- By calling
httpProxy.setMaxSockets(n)
, wheren
is the number of sockets you with to use.