如何使用nodejs监听多个ips?

var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(80, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); 

那么,如果我想听192.168.1.100,就像这样?

 var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(80, '127.0.0.1').listen(80,'192.168.1.100'); 

尝试这个

 var http = require('http'); function handler(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }; http.createServer(handler).listen(80, '127.0.0.1'); http.createServer(handler).listen(80, '192.168.1.100'); // or listen to both instead - thx @FlashThunder // http.createServer(handler).listen(80); 

当http创build套接字时,不能将ips列表分配给一个套接字,这就是为什么您需要为每个ip创build单独的http对象,或者使用0.0.0.0 (或者简单地不定义第二个参数)来监听所有可用的ips。