Here is an example. In this case, the client connects directly to external.js, which then redirects connections to upstream servers (inner.js).
outer.js
var http = require('http'); var httpProxy = require('http-proxy'); var proxies = { foo: new httpProxy.createProxyServer({ target: { host: "foo.com", port: 8080 } }), bar: new httpProxy.createProxyServer({ target: { host: "bar.com", port: 8080 } }) // extend this... }; var findUpstream = function(req){ // TODO return key for lookup in @proxies }; var proxyServer = http.createServer(function (req, res){ var upstream = findUpstream(req); proxies[upstream].web(req, res); }); proxyServer.on('upgrade', function (req, socket, head) { var upstream = findUpstream(req); proxies[upstream].ws(req, socket, head); }); proxyServer.listen(8014);
inner.js
var WebSocketServer = require('ws').Server; var wss = new WebSocketServer({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { console.log('received: %s', message); }); ws.send('something'); });
In this example, you will need to populate findUpstream to return a key, such as foo or bar , based on the data in the request. It is also worth paying attention to error handling when the correct upstream server is not found, but this should illustrate the general idea.
aembke
source share