近日尝试使用node.js的长连接去模拟微信的扫码登录,但是每次超时重连都遇到“socket hang up”的错误,警告一番查阅资料后,终于发现是node.js的连接池惹的祸。
模拟微信登录的核心代码:
function doRequest(resolve,reject){
console.log(`try_time:${retry_time}`);
var login_url = 'login.weixin.qq.com';
var code;
var params = {
'tip': tip,
'uuid': uuid,
'_': Math.round(new Date().getTime()/1000),
};
var paramsString = convertArrayToString(params);
var options = {
rejectUnauthorized:false,
agent:false,
hostname: login_url,
path: '/cgi-bin/mmwebwx-bin/login' + paramsString,
port: 443,
method: 'GET',
headers: {
'User-Agent': 'Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5'
}
};
var req = https.request(options, (res) => {
res.setEncoding('utf8');
res.on('data', (chunk) => {
var pattern_for_code = /window.code=(\d+);/;
pattern_for_code.test(chunk);
code = RegExp.$1;
var pattern_for_redirect_url = /window.redirect_uri=(\S+?);/;
pattern_for_redirect_url.test(chunk);
redirect_uri = RegExp.$1;
console.log(`redirect_uri is:${redirect_uri}`);
console.log(`code inside:${code}`);
});
res.on('end', () => {
console.log(code);
if(code == 201){//scand
tip = 0;
console.log("scand");
doRequest();
}else if(code == 200){//success
console.log("success");
console.log(redirect_uri);
resolve();
}else if(code == 408 && retry_time > 0){//timeout
retry_time--;
setTimeout(doRequest,1000);
}else{
reject(408);
}
})
});
req.on('error',(err)=>{
console.log(err);
})
req.end();
}
上述的代码是一个递归的调用,关键在于agent:false这个选项。node.js在C10K问题的背景下被创造处理,为了网络连接的性能,node.js默认使用连接池,也就是说在上述的代码里面,我们在进入下一级递归的时候,原来调用函数内部的网络连接没有被关闭,
我们必须手动的把网络连接从“网络连接池”中撤出来,让它在进入下一级递归的时候,原来的网络连接就被关闭掉,而agent设置为false,就是把当前的连接从“连接池”中撤出来。
参考资料:
- 《深入浅出node.js》 朴灵