4

I want to completely disable Keep-Alive in Node.js server, but setKeepAlive(false) does not have any effect. This is sample code:

var http = require('http')

var server = http.createServer(function(req, res) {
    res.end('Hello Node.js Server!')
})

server.on('connection', function(socket) {
    socket.setKeepAlive(false)
})

server.listen(8080)

As you can see, after opening http://127.0.0.1:8080, keep-alive header is present: browser-request

Am I doing something wrong?

Info: I am running node v10.1.0, but it also does not work on v8.11.2.

1 Answer 1

7

You can disable HTTP Keep-Alive by setting Connection: close header. This is necessary because Keep-Alive is enabled by default in HTTP 1.1.

var server = http.createServer(function(req, res) {
    res.setHeader('Connection', 'close')
    res.end('Hello Node.js Server!')
})

socket.setKeepAlive() is for TCP Keep-Alive instead of HTTP Keep-Alive, which are two different things. It's very confusing, but TCP Keep-Alive is for keeping an idle connection alive, and HTTP Keep-Alive is for reusing a TCP connection for multiple HTTP requests.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.