Node.js:socks5-https-client-连接失败时尝试使用其他主机

时间:2019-03-02 07:23:38

标签: node.js proxy request socks

很长一段时间以来,我一直在寻找类似的答案,但是没有找到。

我使用此代码,它工作得很好,但仅在首次连接成功时才有效。但是,我的目标是使用相同的凭据重试,但主机和端口不同。 (我使用了多个socks5门,有时它们没有响应,所以我需要尝试另一个)

我尝试调用相同的函数,并且总是出现错误:

  

错误:连接ETIMEDOUT xxx.xxx.xxx.xxx:1081
  在TCPConnectWrap.afterConnect上[按完成状态](net.js:1082:14)
  errno:“ ETIMEDOUT”,
  代码:“ ETIMEDOUT”,
  syscall:“连接”,
  地址:“ xxx.xxx.xxx.xxx”,
  端口:1081}

看起来以前的连接没有完全断开。

这是我用于连接和发布的代码。

var Agent = require('socks5-https-client/lib/Agent');
var request = require('request');

var fails = 0;
var max_fails = 2;

function get_data_via_socks5(client_host,url_to_check, datas, respon) {
	
	///passing array with connection details and backup socks5 hosts
	var api_key = datas.api_key
	var gate = datas.gate

	if(fails==0) {
	var host = datas.host
	var login  = datas.login
	var pass = datas.pass
	var port = datas.port
	
	}
	if(fails==1) {
		
	var host = datas.host2
	var login  = datas.login2
	var pass = datas.pass2
	var port = datas.port2
	
	}
	if(fails==2) {
	var host = datas.host3
	var login  = datas.login3
	var pass = datas.pass3
	var port = datas.port3
	
	}
	

			var jdata = '{somedata:somedata}';


			console.log("Trying to connect by:" , host, " on port: " , port, login, pass  );
			
					var con = request({
								method: 'POST',             
								url: gate, 
								body: jdata,
								headers: {               
								'Authorization': 'Basic ' + Buffer.from("apikey:"+api_key).toString('base64'),
										},
							strictSSL: true,
							agentClass: Agent,
							agentOptions: {
								keepAlive: false,
								socksHost: host, 
								socksPort: port, // Defaults to 1080.

								// Optional credentials
								socksUsername: login,
								sockspassword: pass,
							}
						}, function(err, res) {

									if( err ) {
											
											fails = fails+1
											if(fails<=max_fails) {
												
												console.log( 'Failed to get data using: ', host, "Attempt: ",fails, "ERROR:", err);
												//con.close()
													get_data_via_vpn(client_host,url_to_check,respon);
													return 
												
												
											} else {
											
												
												return console.log( 'Giving up to get data using: ', host, "Failed: ", fails ," attempts");
											
											
											}
									}
									
							if(!err) {		
							var response = JSON.parse( res.body);
							
								console.log(response);
								
								return respon(response);
							}
						});
						
		
	
}

任何帮助将不胜感激,我真的坚持这样做。

0 个答案:

没有答案