编写这个小域名搜索应用程序,它应该按顺序搜索数组中每个项目的.com,但它会继续搜索test1。即使我在搜索功能中执行控制台日志,它告诉我x的值是test2,而测试3.我是否需要删除监听器或什么?
我得到以下输出
domain test1.com
Domain Name: TEST1.COM
domain test2.com
Domain Name: TEST1.COM
domain test3.com
Domain Name: TEST1.COM
app.js
var port = 43;
var net = require('net');
var host = 'whois.internic.net';
var dotCom = new net.Socket();
var c = 0;
var connections = 0;
var dotComStatus;
dotCom.setEncoding('ascii');
var searches = ['test1', 'test2', 'test3'];
search(searches.shift());
function chkconnections(z) {
if (connections <= 0) {
if (searches.length >= 1) {
process.nextTick(function() {
search(searches.shift());
});
}
}
}
function search(x) {
var q = "domain " + x + ".com\r\n";
dotCom.connect(port, host, function() {
dotCom.write(q);
console.log(q);
connections++;
});
dotCom.on('data', function(data) {
c++;
if (c == 2) {
dotComStatus = data.split('\n')[1];
dotCom.on('close', function() {
console.log(dotComStatus);
connections--;
chkconnections();
});
}
});
}
答案 0 :(得分:1)
此代码存在几个明显的问题。首先将close事件放在数据事件中是个坏主意。如果在收到数据之前连接已关闭,则永远不会到达该部分代码。 接下来是
部分存在一个大问题c++;
if (c == 2)
由于您从未将c
重置为0,因此永远不会执行下一行dotComStatus = data.split('\n')[1];
。但随后套接字关闭并触发事件closed
。然后再次执行。
console.log(dotComStatus);
connections--;
chkconnections();
但是dotComStatus
的值没有改变,因为c
等于0.有很多关于如何在NodeJS中执行此连接/数据/结束流的示例。
var port = 43;
var net = require('net');
var host = 'whois.internic.net';
var searches = ['test1', 'test2', 'test3'];
search(searches.shift());
function chkconnections(z) {
if(searches.length > 0)
search(searches.shift());
}
function search(x) {
var dotCom = new net.Socket();
dotCom.setEncoding('ascii');
var q = "domain " + x + ".com\r\n";
dotCom.connect(port, host, function() {
dotCom.write(q);
});
var data = ""; // holding place until socket closes
dotCom.on('data', function(chunk) {
data += chunk; // add chunk to data
});
dotCom.on("end", function() {
// socket closed
dotComStatus = data.split('\n')[7]; // Should be 'Domain Name: blah'
console.log(dotComStatus);
chkconnections(); // move on to next
});
};