繁体   English   中英

node.js 中的 TCP/HTTP 代理

[英]TCP/HTTP proxy in node.js

I'd like to create a simple TCP and HTTP proxy in node.js - For example, the proxy listens on port 8080 and redirects all TCP requests to 127.0.0.1:8181 and all HTTP requests to 127.0.0.0.1:8282

我在 Google 上找到了一个简单的 HTTP 代理的代码片段,代码只有 20 行:

var http = require('http');

http.createServer(function(request, response) {
  var proxy = http.createClient(80, request.headers['host'])
  var proxy_request = proxy.request(request.method, request.url, request.headers);
  proxy_request.addListener('response', function (proxy_response) {
    proxy_response.addListener('data', function(chunk) {
      response.write(chunk, 'binary');
    });
    proxy_response.addListener('end', function() {
      response.end();
    });
    response.writeHead(proxy_response.statusCode, proxy_response.headers);
  });
  request.addListener('data', function(chunk) {
    proxy_request.write(chunk, 'binary');
  });
  request.addListener('end', function() {
    proxy_request.end();
  });
}).listen(8080);

所以基本上我需要在8080上监听任何类型的请求,猜猜是TCP还是HTTP,然后将请求代理到正确的路径。 使用上面的代码片段有什么提示吗?

谢谢

nodejitsu开源了一个node-http-proxy ,我想你可以试试。 它已记录在案,正在积极开发。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM