node.js 侦听不同的 IP 地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15003947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:39:26  来源:igfitidea点击:

Listen to a different IP address

node.jsexpress

提问by Randomblue

This is my code:

这是我的代码:

var server = express();

// Create the HTTP server
http
    .createServer(server)
    .listen(80, '10.10.10.10');

Once the server has been started, how can I dynamically change the listened IP address, say to 11.11.11.11instead of 10.10.10.10. Is there an "unlisten" method?

服务器启动后,如何动态更改侦听的 IP 地址,说 to11.11.11.11而不是10.10.10.10. 有“不听”的方法吗?

回答by supernova

you have to use server.close() not app.close()..

你必须使用 server.close() 而不是 app.close()。

var express = require('express')
  , http = require('http')
  , app = express()
  , server = http.createServer(app)

app.get('/',function(req,res){
  ...
})

server.listen(8000,'127.0.0.1',function(){
 server.close(function(){
   server.listen(8001,'192.168.0.202')
 })
})

should work

应该管用

回答by John Zwinck

I think the "unlisten" function you're looking for is called "close": http://nodejs.org/api/http.html#http_server_close_callback

我认为您正在寻找的“不听”功能称为“关闭”:http: //nodejs.org/api/http.html#http_server_close_callback

回答by Jean-Philippe Leclerc

What your are trying to accomplish is quite non-standard in my opinion. I would suggest server.close(). Close will wait all request to finish and trigger the "close" event. You can bind on that event to listen on the new IP. This is quite weird tho.

在我看来,你想要完成的事情是非常不标准的。我建议server.close()。关闭将等待所有请求完成并触发“关闭”事件。您可以绑定该事件以侦听新 IP。这很奇怪。

回答by doonsnboons

app.listen(3000,'0.0.0.0',function(){
  console.log('Server running at http://127.0.1.1:8000/')
})

will work with express

将与快递一起工作