4

I've been testing the functionality of keepalive in Node.js TCP sockets. It seems that I'm missing something here!

Here is my server code:

var net = require('net');
function accept(socket) {
    socket.setKeepAlive(false);
    socket.on('data', function(data) {
        console.log("DATA");
        console.log(data);
    });
    socket.on('error', function (e) {
        console.log("ERROR");
        console.log(e);
    });
    socket.on('close', function () {
        console.log("CLOSE");
    });
    socket.on('end', function () {
        console.log("END");
    });
    socket.write("Hi");
}
var server = net.createServer(accept);
server.listen(8011);

And it is my client code:

var net = require('net');
var socket = new net.Socket();
socket.setKeepAlive(false);
socket.on('data', function(data) {
    console.log("DATA");
    socket.write(data);
});
socket.on('error', function (e) {
    console.log("ERROR");
    console.log(e);
});
socket.on('close', function () {
    console.log("CLOSE");
});
socket.on('end', function () {
    console.log("END");
});
socket.connect(8011, '127.0.0.1');

Why does the server (or the client) not close the connection even if no data has been sent or received for a long time (120 sec)?

I'm using Node.js version 0.10.5!

1
  • Your expectation is incorrect. Disabling it doesn't mean that idle connections will be timed out. Enabling it means that idle connections wont be timed out. Commented Sep 14, 2016 at 0:07

1 Answer 1

3

Because keep-alive works at a lower level. It sends a check packet without any data payload and if there's no answer, then the connection is considered broken.

Try doing the same, but unplug your Ethernet cable from one of the machines.

Edit 0:

Sorry, misread your code a bit.

TCP keep-alive feature is often called "dead peer detection". Read about its mechanics, for example, here. With keep-alive disabled there's nothing in TCP itself that would force the connection to be closed after any inactivity timeout. It's intermediate devices like NAT-ing routers that may expire state and break your connection, not the communicating ends themselves.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.