node.js – 如何在NodeJS中测试socket.setKeepAlive

我试图在NodeJS中测试setKeepAlive()的功能.我在同一本地网络中的不同机器上运行Server.js和client.js.然后,我关闭了客户端计算机上的wifi连接(断开互联网连接). 15分钟后,仍然没有任何消息被抛出.这是为什么?没有setKeepAlive()工作?

这是服务器和客户端的代码:

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);

最佳答案 我将使用setInterval(sendKeepAliceFunc,delay)和socket.setTimeout()自己实现keep_alive

keep_alive消息之间的延迟应该足够大(~10000ms),如果延迟

点赞