How to test socket.setKeepAlive in NodeJS

Viewed 4404

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);
1 Answers
Related