7

引自TCP keepalive HowTo

为了理解 TCP keepalive(我们将称之为 keepalive)的作用,您只需阅读名称:keep TCP alive。这意味着您将能够检查已连接的套接字(也称为 TCP 套接字),并确定连接是否仍在运行或已断开

那么为什么当互联网连接中断时,下面的代码没有抛出一些东西呢?

var tls = require('tls');

var socket = tls.connect(443, "google.com", function connected() {
  console.log('connected');
});

socket.setNoDelay(true);
socket.setKeepAlive(true, 0);
socket.setTimeout(0, function(){
  console.log('timeout');
});
socket.on('data', function(data) {
  console.log(data);
});
socket.on('close', function() {
  console.error("close");
});
socket.on('error', function(err) {
  console.error("error", err);
});

在 MacOS/Debian 上测试,使用 NodeJS v0.10.17

4

2 回答 2

7

引用man 7 tcp

tcp_keepalive_time(整数;默认值:7200;从 Linux 2.2 开始)

在 TCP 开始发送保持活动探测之前,连接需要空闲的秒数。仅当启用 SO_KEEPALIVE 套接字选项时才发送保持活动状态。默认值为 7200 秒(2 小时)。启用 keep-alive 后,大约再过 11 分钟(9 次探测间隔 75 秒)后,将终止空闲连接。

所以大约 10 分钟后(在 MacOS 10.8 上)节点发出了一个错误:

error { [Error: read ETIMEDOUT] code: 'ETIMEDOUT', errno: 'ETIMEDOUT', syscall: 'read' }
于 2013-09-07T22:23:58.717 回答
2

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

这是一个模块,可让您基于每个套接字配置 TCP_KEEPINTVL 和 TCP_KEEPCNT。

提供对 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)
});
于 2015-08-05T08:38:37.037 回答