一、http、https
(1)、利用 forever: true,实现长连接
const request = require('request')
const util = require('util')
// proxy配置
const agentConfig = {
ip: '106.22.22.222',
port: '808'
}
const proxy = util.format('http://%s:%d', agentConfig.ip, agentConfig.port);
request({
method: 'post',
url: 'http://127.0.0.1:3000/api/logins',
proxy,
forever: true, // 长链接
}, (error, response, body) => {
console.log(body)
})
(2)、利用 hpagent 依赖的 keepAlive 属性,实现长连接
const request = require('request');
const { HttpProxyAgent, HttpsProxyAgent } = require('hpagent');
const util = require('util');
// proxy配置
const agentConfig = {
ip: '106.22.22.222',
port: '808'
}
// 请求地址
const url = 'http://127.0.0.1:3000/api/logins'
const isHttps = (new URL(url)).protocol === 'https:'
const proxy = util.format('http://%s:%d', agentConfig.ip, agentConfig.port);
// http proxy
const httpAgent = new HttpProxyAgent({
keepAlive: true, // 配置这个长链接
keepAliveMsecs: 5000,
maxSockets: 256,
maxFreeSockets: 256,
scheduling: 'lifo',
proxy
})
// https proxy
const httpsAgent = new HttpsProxyAgent({
keepAlive: true,
keepAliveMsecs: 5000,
maxSockets: 256,
maxFreeSockets: 256,
scheduling: 'lifo',
proxy
})
request({
method: 'post',
url: 'http://127.0.0.1:3000/api/logins',
agent: isHttps ? httpsAgent : httpAgent
}, (error, response, body) => {
console.log(body)
})
二、socks5
(1)、第一种
const request = require('request')
const httpAgent = require('socks5-http-client/lib/Agent')
const httpsAgent = require('socks5-https-client/lib/Agent')
// 请求地址
const url = 'http://127.0.0.1:3000/api/logins'
const isHttps = (new URL(url)).protocol === 'https:'
// proxy配置
const socks5Config = {
ip: '106.22.22.222',
port: '1080',
socksUsername: 'guest', // 账号
socksUsername: '123456' // 密码
}
request({
method: 'post',
url,
agentClass: isHttps ? httpsAgent : httpAgent,
agentOptions: {
socksHost: socks5Config.ip,
socksPort: socks5Config.port,
socksUsername: socks5Config.socksUsername,
socksPassword: socks5Config.socksPassword
}
}, (error, response, body) => {
console.log(body)
})
(2)、第二种(同时支持socks5、http、https代理)
const request = require('request');
const { SocksProxyAgent } = require('socks-proxy-agent')
// proxy配置
const agent = new SocksProxyAgent({
host: '106.22.22.222',
port:'1080',
userId: 'guest',
password: '123456'
})
request({
method: 'post',
url: 'http://127.0.0.1:3000/api/logins',
agent
}, (error, response, body) => {
console.log(body)
})
⚠️长连接:
1、request依赖中,长链接仅同步下生效,for循环并行不生效
2、socks5测试无法实现长链接,每次请求将重新握手;大神们若有解决方案,还请吝啬留言交流!!
到这里就大工告成了,有用的话麻烦关注收藏一下🌹🌹🌹~