Pregunta

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!

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top