Node Http Proxy Web Socket Balance

I need to balance websocket at the application level. Allows you to send a websocket request based on the message I received, decode it on a proxy server and then use this data to send to another socket server using some logic.

But I canโ€™t do it. This is the initial code I wrote and am trying to do this. This is a server

var http = require('http'); var httpProxy = require('http-proxy'); var WebSocket = require('ws'); 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'); }); var proxy = httpProxy.createServer({target: 'ws://localhost:8080', ws:true}); var server = httpProxy.createServer(function(req, res) { //SOME LOGIC HERE TO PARSE WS DATA AND SEND TO WS SERVER proxy.ws(req, res, { target: 'ws://localhost:8080'}); }).listen(8014); 

CLIENT

 var http = require('http'); var httpProxy = require('http-proxy'); var WebSocket = require('ws'); var ws = new WebSocket('ws://localhost:8014/'); ws.on('open', function () { ws.send("CLIENT"); }); ws.on('message', function (msg) { console.log(msg); }); 
+7
web-services proxy sockets
source share
1 answer

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.

+2
source

All Articles