Why NodeJS KeepAlive does not seem to work as expected?

前端 未结 2 680
一生所求
一生所求 2021-01-12 17:20

Quoted from TCP keepalive HowTo:

In order to understand what TCP keepalive (which we will just call keepalive) does, you need do nothing more than r

2条回答
  •  感动是毒
    2021-01-12 17:46

    https://www.npmjs.com/package/net-keepalive

    Here is a module which lets you configure TCP_KEEPINTVL and TCP_KEEPCNT per-socket basis.

    Provides high-level access to socket options like TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT

    var Net = require('net')
      , NetKeepAlive = require('net-keepalive')
    ;
    
    // Create a TCP Server
    var srv = Net.createServer(function(s){>
      console.log('Connected %j', s.address())
      // Doesn't matter what it does
      s.pipe(s)
    });
    
    // Start on some port
    srv.listen(1337, function(){
      console.log('Listening on %j', srv.address())
    });
    
    // Connect to that server
    var s = Net.createConnection({port:1337}, function(){
      console.log('Connected to %j', s.address())
    
      //IMPORTANT: KeepAlive must be enabled for this to work
      s.setKeepAlive(true, 1000)
    
      // Set TCP_KEEPINTVL for this specific socket
      NetKeepAlive.setKeepAliveInterval(s, 1000)
    
      // and TCP_KEEPCNT
      NetKeepAlive.setKeepAliveProbes(s, 1)
    });
    

提交回复
热议问题