0

编写这个小型域搜索应用程序,它应该按顺序搜索数组中每个项目的 .com,但它一直在搜索 test1。即使我在搜索功能中执行控制台日志,它也会告诉我 x 的值是 test2 和 test 3。我需要删除侦听器还是什么?

我得到以下输出

 domain test1.com

 Domain Name: TEST1.COM
 domain test2.com

 Domain Name: TEST1.COM
 domain test3.com

 Domain Name: TEST1.COM

应用程序.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();
             });
        }
   });
}   
4

1 回答 1

1

这段代码有几个明显的问题。首先将关闭事件放在数据事件中是一个坏主意。如果连接在接收到数据之前关闭,那段代码将永远无法到达。接下来是这个部分有一个大问题

c++;
if (c == 2)

由于您从未重置为 0,因此永远不会执行c下一行。dotComStatus = data.split('\n')[1];但随后套接字关闭并closed触发事件。这又被执行了。

  console.log(dotComStatus);
  connections--;
  chkconnections();

但是自从等于 0以来,值dotComStatus并没有改变。有很多示例说明如何执行 NodeJS 中常见的连接/数据/结束流。c

 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
    });
};
于 2013-07-27T04:52:16.957 回答