4

According to the documentation calling server.close()

Stops the server from accepting new connections and keeps existing connections.

So my code is:

var http = require('http');

var server = http.createServer(function (req, res) {
    console.log('path: ' + req.url);

    server.getConnections(function (err, count) {
        console.log('connections: ' + count);

        res.end('end');

        server.close();
    });
});

server.listen(3000);

server.on('close', function () {
    console.log('server closed');

    process.exit(1);
});

Here is what I get after making two requests to http://localhost:3000:

> path: /                              connections: 1                   
> path: /                              connections: 1                   
> 
>                                      net.js:1236                         
>     throw new Error('Not running'); 
>           ^                          Error: Not running                  
>     at Server.close (net.js:1236:11)

This means that the second connection is being accepted even though during the first one I have called server.close().

What am I missing?

EDIT: As per @gino9's comment even if I close the server outside the getConnections callback, the problem remains.

var server = http.createServer(function (req, res) {
    console.log('path: ' + req.url);

    res.end(new Date() + '');

    server.close();
});
simich
  • 358
  • 3
  • 10
  • Catch the (specific) exception or keep track of the manual-close via a flag? – user2864740 Nov 04 '14 at 17:13
  • Note that you are calling the server.close() from inside the callback of the asynchronous getConnections and then you cannot be sure that the server gets closed before the handling of the second request. – matteo Nov 04 '14 at 17:16
  • @user2864740 I do that and there's no exception but incoming requests keep being accepted and served. My question is why does this happen? – simich Nov 04 '14 at 17:17
  • @gino9 Moving `server.close()` outside doesn't solve it. – simich Nov 04 '14 at 17:23

1 Answers1

2

You posted the solution in your question.

Stops the server from accepting new connections and keeps existing connections.

In other words, connections that you have opened are kept open until they time out. This is called a keep-alive connection.

See this answer how-do-i-shutdown-a-node-js-https-server-immediately for a way to close all your connections immediately after calling the server.close(); method.

Community
  • 1
  • 1
bastos.sergio
  • 6,684
  • 4
  • 26
  • 36
  • I was initially about to disagree with your suggestion but after double-checking I realized what was happening. I was making F5 requests, so with the `keep-alive` header this was the same connection. Trying with a different browser showed that **new** connections were really rejected. Thanks! – simich Nov 04 '14 at 17:32