无法关闭服务器(nodeJS)

时间:2013-09-22 06:22:17

标签: javascript node.js

为什么我无法通过在浏览器中请求localhost:13777 / close来关闭服务器(它继续接受新的请求),但它会在超时15000时正常关闭?节点版本为0.10.18。我遇到了这个问题,尝试使用文档中的代码示例来处理域的异常处理(每当我第二次尝试请求错误页面时,它都会给我'运行'错误),最后来到这段代码。

var server

server = require("http").createServer(function(req,res){

  if(req.url == "/close")
  {
    console.log("Closing server (no timeout)")

    setTimeout(function(){
      console.log("I'm the timeout")
    }, 5000);    

    server.close(function(){
      console.log("Server closed (no timeout)")
    })    

    res.end('closed');
  }
  else
  {
    res.end('ok');
  }

});

server.listen(13777,function(){console.log("Server listening")});

setTimeout(function(){

  console.log("Closing server (timeout 15000)")
  server.close(function(){console.log("Server closed (timeout 15000)")})

}, 15000);

2 个答案:

答案 0 :(得分:2)

服务器仍在等待来自客户端的请求。客户端正在使用HTTP keep-alive。

我认为您会发现,虽然现有客户端可以发出新请求(因为连接已经建立),但其他客户端将无法做到。

答案 1 :(得分:1)

Nodejs没有在http.Server之上实现复杂的服务层。通过调用server.close(),您指示服务器不再接受任何“新”连接。发出HTTP Connection:keep-alive时,服务器将保持套接字打开,直到客户端终止或达到超时。其他客户将无法发出请求

可以使用server.setTimeout() https://nodejs.org/api/http.html#http_server_settimeout_msecs_callback

更改超时

请记住,如果客户端在close事件之前创建了连接,则可以继续使用该连接。

似乎很多人不喜欢这个当前的功能,但这个问题已经开放了很长一段时间:

https://github.com/nodejs/node/issues/2642

相关问题