TCP套接字客户端通过nodejs上的代理

时间:2015-11-14 16:22:13

标签: node.js network-programming

我需要与smtp服务器建立tcp套接字连接。是否可以通过nodejs上的代理服务器进行连接?有没有可用的npm模块?我根本找不到任何东西。

var net = require('net');

var HOST = '127.0.0.1';
var PORT = 6969;

var client = new net.Socket();
client.connect(PORT, HOST, function() {
    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    client.write('I am here!');
});

// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {

    console.log('DATA: ' + data);

});

// Add a 'close' event handler for the client socket
client.on('close', function() {
    console.log('Connection closed');
});

2 个答案:

答案 0 :(得分:1)

net.sockettls.connectdgram没有代理支持。

将它与代理一起使用的最简单方法是用proxychains或类似的东西替换一些libc函数。

var client = require('tls')
.connect(443, 'www.facebook.com', function() {
  console.log('connected');
  client.write('hello');
})
.on('data', function(data) {
  console.log('received', data.toString());
})
.on('close', function() {
  console.log('closed');
});
  

proxychains node fit.js

connected
received HTTP/1.1 400 Bad Request
...
closed

答案 1 :(得分:0)

是的,可以使用其中一个NPM模块:

http-proxy-agent :HTTP端点的HTTP(s)代理http.Agent实现

https-proxy-agent :HTTPS端点的HTTP(s)代理http.Agent实现

pac-proxy-agent :用于HTTP和HTTPS的PAC文件代理http.Agent实现

socks-proxy-agent :用于HTTP和HTTPS的SOCKS(v4a)代理http.Agent实现

HTTPS代理示例:

var url = require('url');
var WebSocket = require('ws');
var HttpsProxyAgent = require('https-proxy-agent');

// HTTP/HTTPS proxy to connect to
var proxy = process.env.http_proxy || 'http://168.63.76.32:3128';
console.log('using proxy server %j', proxy);

// WebSocket endpoint for the proxy to connect to
var endpoint = process.argv[2] || 'ws://echo.websocket.org';
var parsed = url.parse(endpoint);
console.log('attempting to connect to WebSocket %j', endpoint);

// create an instance of the `HttpsProxyAgent` class with the proxy server information
var opts = url.parse(proxy);

var agent = new HttpsProxyAgent(opts);

// finally, initiate the WebSocket connection
var socket = new WebSocket(endpoint, { agent: agent });

socket.on('open', function () {
  console.log('"open" event!');
  socket.send('hello world');
});

socket.on('message', function (data, flags) {
  console.log('"message" event! %j %j', data, flags);
  socket.close();
});

我希望这会有所帮助。