代码之家  ›  专栏  ›  技术社区  ›  Alexander Bird

node.js::hostname在“listen”函数中做什么?

  •  9
  • Alexander Bird  · 技术社区  · 15 年前

    我拥有两个域,abc.com和xyz.com(不是我真正拥有的域,但它们是一个例子)。它们都指向相同的IP地址。以下是我的服务器JS文件:

    var sys=require('sys'),
      http=require('http'),
      settings=require('./settings');
    
    
    
    var srv = http.createServer(function(req, res) {
        var body="<b>Hello World!</b>"
        res.writeHead(200, {
            'content-length': body.length,
              'content-type': 'text/html',
              'stream': 'keep-alive',
              'accept': '*/*'
              }
          );
        res.end(body);
      });
    
    srv.listen(8000, 'abc.com' ); // (settings.port, settings.hostname);
    

    然后我参观 http://abc.com:8000/ http://xyz.com:8000/ 它们都会显示网页。我以为我只能在abc.com上看到这个页面,因为我把它设置为主机名。

    但是,当我将“127.0.0.1”作为主机名时,我只能通过服务器本身的wget查看页面。

    那又怎么样 主机名参数是什么?

    1 回复  |  直到 15 年前
        1
  •  6
  •   Alexander Bird    15 年前

    NET.JS中定义listen函数的以下代码段是相关的:

    // the first argument is the port, the second an IP    
    var port = arguments[0];
    dns.lookup(arguments[1], function (err, ip, addressType) {
      if (err) {
        self.emit('error', err);
      } else {
        self.type = addressType == 4 ? 'tcp4' : 'tcp6';
        self.fd = socket(self.type);
        bind(self.fd, port, ip);
        self._doListen();
      }
    });
    

    所以基本上提供一个URL作为主机名参数是不允许共享主机的。所有node.js所做的工作都是将主机名解析为一个IP地址——在我的例子中,两个域都指向同一个IP,这两个都可以工作。

    要我做共享托管,我必须找到另一种方法。

    推荐文章