为什么 NodeJS KeepAlive 似乎没有按预期工作? [英] Why NodeJS KeepAlive does not seem to work as expected?

查看:34
本文介绍了为什么 NodeJS KeepAlive 似乎没有按预期工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用自 TCP keepalive HowTo:

为了了解什么是 TCP keepalive(我们将称之为keepalive) 可以,您只需要阅读名称即可:keep TCP活.这意味着您将能够检查连接的套接字(也称为 TCP 套接字),并确定连接是否正常仍然正常运行,或者如果它坏了.

In order to understand what TCP keepalive (which we will just call keepalive) does, you need do nothing more than read the name: keep TCP alive. This means that you will be able to check your connected socket (also known as TCP sockets), and determine whether the connection is still up and running or if it has broken.

那么为什么以下代码在互联网连接中断时不抛出任何东西?

So why is the following code not throwing something when the internet connection is broken?

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

Tested on MacOS/Debian, with NodeJS v0.10.17

推荐答案

引用 man7 tcp:

tcp_keepalive_time(整数;默认值:7200;自 Linux 2.2)

tcp_keepalive_time (integer; default: 7200; since Linux 2.2)

在 TCP 开始发送保持活动探测之前连接需要空闲的秒数.只有在启用 SO_KEEPALIVE 套接字选项时才会发送保持活动.默认值为 7200 秒(2 小时).启用保持连接后,空闲连接将在大约 额外 11 分钟(9 次探测,间隔 75 秒)后终止.

The number of seconds a connection needs to be idle before TCP begins sending out keep-alive probes. Keep-alives are only sent when the SO_KEEPALIVE socket option is enabled. The default value is 7200 seconds (2 hours). An idle connection is terminated after approximately an additional 11 minutes (9 probes an interval of 75 seconds apart) when keep-alive is enabled.

因此在大约 10 分钟后(在 MacOS 10.8 上)节点发出错误:

So after ~10 minutes (on MacOS 10.8) node emitted an error:

error { [Error: read ETIMEDOUT] code: 'ETIMEDOUT', errno: 'ETIMEDOUT', syscall: 'read' }

这篇关于为什么 NodeJS KeepAlive 似乎没有按预期工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆