2013-08-03 26 views
5
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/'); 

Vì vậy, nếu tôi muốn nghe 192.168.1.100, giống như thế này?cách sử dụng nodejs nghe nhiều 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').listen(80,'192.168.1.100'); 

Trả lời

4

Hãy thử điều này

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); 
5

Như http tạo socket, bạn không thể gán danh sách ip với một ổ cắm, đó là lý do tại sao bạn cần phải tạo các đối tượng http riêng biệt cho mỗi ip, hoặc sử dụng 0.0.0.0 (hoặc đơn giản là không xác định tham số thứ hai) để nghe trên tất cả các ips có sẵn.

Các vấn đề liên quan