强制关闭node.js http服务器中的所有连接 [英] Force close all connections in a node.js http server

查看:721
本文介绍了强制关闭node.js http服务器中的所有连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下方法创建了一个http服务器:

I have an http server created using:

var server = http.createServer()

我想关闭服务器。据推测,我打电话来这样做:

I want to shut down the server. Presumably I'd do this by calling:

server.close()

但是,这只会阻止服务器接收任何新的http连接。它不会关闭任何仍然打开的。 http.close()接受回调,并且在所有打开的连接实际断开之前,该回调不会执行。有没有办法强制关闭所有东西?

However, this only prevents the server from receiving any new http connections. It does not close any that are still open. http.close() takes a callback, and that callback does not get executed until all open connections have actually disconnected. Is there a way to force close everything?

问题的根源在于我有Mocha测试在他们的设置中启动了一个http服务器( beforeEach())然后在他们的拆解中关闭它( afterEach())。但是因为只是调用 server.close()不会完全关闭,后续的 http.createServer()经常导致 EADDRINUSE 错误。等待 close()完成也不是一个选项,因为打开连接可能需要很长时间才能超时。

The root of the problem for me is that I have Mocha tests that start up an http server in their setup (beforeEach()) and then shut it down in their teardown (afterEach()). But since just calling server.close() won't fully shut things down, the subsequent http.createServer() often results in an EADDRINUSE error. Waiting for close() to finish also isn't an option, since open connections might take a really long time to time out.

我需要一些强制关闭连接的方法。我能够做这个客户端,但强制关闭我的所有测试连接,但我宁愿在服务器端做,即只是告诉http服务器硬关闭所有套接字。

I need some way to force-close connections. I'm able to do this client-side, but forcing all of my test connections to close, but I'd rather do it server-side, i.e. to just tell the http server to hard-close all sockets.

推荐答案

你需要


  1. 订阅服务器的连接事件并将打开的套接字添加到数组

  2. 通过订阅他们的<跟踪打开的套接字code>关闭事件并从阵列中移除已关闭的事件

  3. 调用销毁当您需要终止服务器时剩余的打开套接字

  1. subscribe to the connection event of the server and add opened sockets to an array
  2. keep track of the open sockets by subscribing to their close event and removing the closed ones from your array
  3. call destroy on all of the remaining open sockets when you need to terminate the server

您还有机会在子进程中运行服务器并退出你需要的那个过程。

You also have the chance to run the server in a child process and exit that process when you need.

这篇关于强制关闭node.js http服务器中的所有连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆