Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test socket.setKeepAlive in NodeJS

I tried to test the function of setKeepAlive() in NodeJS. I ran Server.js and client.js on different machines within same local network. Then, I turned off the wifi connection on the client machine (break the internet connection). After 15 minutes, there is still no message thrown. Why is that? Didn't setKeepAlive() work?

Here is the code of the server and client:

Client.js

var net = require('net');
var HOST = '192.168.0.16';
var PORT = 8333;

var client = net.connect(PORT, HOST, function connected(){
    console.log('connected');
});

client.setKeepAlive(true, 1);
client.write('hi server');

client.on('data', function(data) {
    console.log('Received' + data);
});

client.on('close', function(){
    console.error('connection closed');
)};

client.on('error', function(err){
    console.error('error', err);
});

Server.js

var net = require('net');
var HOST = '192.168.0.16';
var PORT = 8333;

net.createServer(function(sock) {
    console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);

    sock.on('data', function(data) {
        console.log('DATA ' + sock.remoteAddress + ': ' + data);
        sock.write('hi client');
    });

    sock.on('close', function(data) {
        console.log('CLOSED: ' +
        sock.remoteAddress + ' ' + sock.remotePort);
    });

    sock.on('error', function(error){
        console.log('error', error);
    });

}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);
like image 436
Shawn Neal Avatar asked Oct 21 '22 18:10

Shawn Neal


1 Answers

I would implement keep_alive by myself using both setInterval(sendKeepAliceFunc, delay), and socket.setTimeout()

Delay between keep_alive message should be big enough (~10000ms), it not valid if delay < round trip (?)

I think the original keepalive feature is not reliable. I have success enable it on other programming language (C# and C) and I can trace network and see KEEP_ALIVE packets, but then it NOT work in some circumstances (special network configuration, people may run app in virtual machine, ...)

So I suggest implement it by yourself, you can implement a your own socket with the same APIs but also has your new keepalive feature.

like image 173
damphat Avatar answered Oct 27 '22 10:10

damphat