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
I found this snippet on Google for a simple HTTP proxy in 20 lines of code:
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');
开发者_StackOverflow });
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);
So basically I need to listen for any sort of request on 8080, guess if it's TCP or HTTP, and then proxy the request to the right path. Any tips using the snippet above?
Thanks
nodejitsu has open-sourced a node-http-proxy which I think you try instead. It is documented, actively developed.
精彩评论