Advertisement
SWAG98

Node.js proxy round robin distribution

Apr 18th, 2018
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const http = require("http");
  2. const URL = require("url");
  3. /*Function createRoundRobinProvider(port,proxies)
  4.     Creates a Round Robin Distributing Server that Devides the Requests to the Proxies
  5.    
  6.     Parameters:
  7.         port        - The port the server uses
  8.         proxies     - The proxies in an array of host-port objects [{host:"host",port:0},{host:"host",port:1}]...
  9.    
  10.     Returns:
  11.         trus
  12.        
  13.     Events:
  14.         request     - fired on incomming request, returns the request and the relay Proxy
  15.         response    - fired on outgoing proxy response, returns the response and the relay Proxy
  16. */
  17. function proxyDistributior(port,proxies){
  18.     this.proxy_index = 0;
  19.     self = this;
  20.     http.createServer((request,response)=>{
  21.         if(self.proxy_index >= proxies.length){self.proxy_index = 0;}
  22.         var proxy = proxies[self.proxy_index++];
  23.         self.emit("request",request,proxy);
  24.         console.log(request.url)
  25.         var proxy_request = http.request({
  26.             host:proxy.host,
  27.             port:proxy.port,
  28.             path:URL.parse(request.url).path,
  29.             method:request.method,
  30.             headers:request.headers
  31.         },(proxy_response)=>{
  32.             self.emit("response",proxy_response,proxy);
  33.             proxy_response.on('data',(chunk)=>{
  34.                 response.write(chunk);
  35.             });
  36.             proxy_response.on('end',_=>{
  37.                 response.end();
  38.             });
  39.             response.writeHead(proxy_response.statusCode,proxy_response.headers);
  40.         });
  41.         request.on('data',(chunk)=>{
  42.             proxy_request.write(chunk);
  43.         });
  44.         request.on('end',_=>{
  45.             proxy_request.end();
  46.         });
  47.     }).listen(port);
  48.     return this;
  49. }
  50. util.inherits(proxyDistributior,require("events").EventEmitter);
  51.  
  52. this.proxyDistributor= proxyDistributior;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement