Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force close all connections in a node.js http server

Tags:

http

node.js

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()

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?

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.

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.

like image 342
Matt Zukowski Avatar asked Sep 18 '13 14:09

Matt Zukowski


People also ask

How do I stop HTTP server in NodeJS?

The server. close() method stops the HTTP server from accepting new connections. All existing connections are kept.

How do I close a Web server?

To stop the server, I just press Ctrl+C.

Where does HTTP terminate?

In HTTP 1.1, the server does not close the connection after sending the response UNLESS the client sent a Connection: close request header, or the server sent a Connection: close response header. If such a response header exists, the client must close its end of the connection after receiving the response.

How do I stop NodeJS from listening?

server. close() prevents new connections and waits until all the clients are closed. To forcibly kill a node server you need to call server. close() and then close all the open connections from the server end.


2 Answers

For reference for others who stumble accross this question, the https://github.com/isaacs/server-destroy library provides an easy way to destroy() a server (using the approach described by Ege).

like image 34
ploer Avatar answered Sep 29 '22 23:09

ploer


You need to

  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.

like image 71
Ege Özcan Avatar answered Sep 30 '22 00:09

Ege Özcan