I have written http proxy in node.js running on port 80. All I need is to redirect socket.io traffic to port 9090 and standard http traffic to Apache on 8080. This is my proxy code:
httpProxy = require('http-proxy');
httpProxy.createServer(function (req, res, proxy) {
if (req.url.match(/socket.io/)) {
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 9090
});
} else {
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 8080
});
}
}).listen(80);
Everything works, but io.socket falls back to xhr-polling.
http://localhost/client.htm - falls back to xhr-polling
file:///C:/.../client9090.htm - still uses websocket
socket.io app is running on port 9090, client.htm connects to 80 and client9090.htm connects directly to 9090.
It looks like a node-http-proxy makes socket.io app to work in xhr-polling mode. Client is Chrome v.25
socket.io app code
var io = require('socket.io').listen(9090);
io.on('connection', function (socket) {
socket.on('hi!', function (data) {
console.log(data);
socket.emit('news');
});
socket.on('ahoj', function (data) {
console.log(data);
});
});
client.htm code
<script src="http://localhost/socket.io/socket.io.js"></script>
<script>
var chat = io.connect('http://localhost')
chat.on('connect', function () {
chat.emit('hi!');
});
chat.on('news', function () {
chat.emit('ahoj',{a:1,b:2});
});
</script>
client9090.htm is the same but localhost is replaced by localhost:9090
As I said, everythig works well, only problem is, that node-http-proxy makes to fall back from websockets to xhr-polling. Can anyone help?
According to https://npmjs.org/package/http-proxy, when adding a callback to the httpProxy.createServer(), you have to manually proxy 'upgrade' events, so something like this:
httpProxy = require('http-proxy');
// added `var server =` here
var server = httpProxy.createServer(function (req, res, proxy) {
if (req.url.match(/socket.io/)) {
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 9090
});
} else {
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 8080
});
}
}).listen(80);
// added upgrade listener section here:
server.on('upgrade', function (req, socket, head) {
server.proxy.proxyWebSocketRequest(req, socket, head);
});
However, for the usage you described above, you don't even need the callback function - you could just as easily do something like this:
httpProxy = require('http-proxy');
var options = {
pathnameOnly: true,
router: {
'/wiki': '127.0.0.1:8001',
'/blog': '127.0.0.1:8002',
'/api': '127.0.0.1:8003'
}
}
var proxyServer = httpProxy.createServer(options);
proxyServer.listen(80);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With