node.js 中的 setKeepAlive 如何工作以及如何实现? [英] How does setKeepAlive in node.js work and how to implement it?

查看:31
本文介绍了node.js 中的 setKeepAlive 如何工作以及如何实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法理解 Node.js 网络套接字中 setKeepAlive 方法的原理.initialDelay 结束后会发生什么?

Cannot understand the philosophy of setKeepAlive method in Node.js' net sockets. What happens after initialDelay finishes?

推荐答案

此方法控制底层 TCP 套接字上的 TCP 保持活动功能.查看这篇文章,了解有关 TCP Keepalive 的信息.下面的代码片段解释了 initialDelay(keepalive 计时器")的作用:

This method controls TCP keep-alive functionality on the underlying TCP socket. Check out this article for information on TCP Keepalive. Here's a snippet that explains what initialDelay (the "keepalive timer") does:

keepalive 的概念很简单:当你建立一个 TCP 连接时,你关联了一组定时器.其中一些定时器处理保活程序.当保活计时器达到零时,您向对等方发送一个保活探测数据包,其中没有数据并且 ACK 标志打开.由于 TCP/IP 规范,您可以这样做,作为一种重复的 ACK,并且远程端点将没有参数,因为 TCP 是面向流的协议.另一方面,您将收到来自远程主机的回复(它根本不需要支持 keepalive,只需要 TCP/IP),没有数据和 ACK 设置.

2.1. What is TCP keepalive?

The keepalive concept is very simple: when you set up a TCP connection, you associate a set of timers. Some of these timers deal with the keepalive procedure. When the keepalive timer reaches zero, you send your peer a keepalive probe packet with no data in it and the ACK flag turned on. You can do this because of the TCP/IP specifications, as a sort of duplicate ACK, and the remote endpoint will have no arguments, as TCP is a stream-oriented protocol. On the other hand, you will receive a reply from the remote host (which doesn't need to support keepalive at all, just TCP/IP), with no data and the ACK set.

如果您收到对 keepalive 探测的回复,您可以断言连接仍在运行,而无需担心用户级实现.事实上,TCP 允许您处理流,而不是数据包,因此零长度数据包对用户程序没有危险.

If you receive a reply to your keepalive probe, you can assert that the connection is still up and running without worrying about the user-level implementation. In fact, TCP permits you to handle a stream, not packets, and so a zero-length data packet is not dangerous for the user program.

此过程很有用,因为如果其他对等方失去连接(例如通过重新启动),即使您没有流量,您也会注意到连接已断开.如果您的对等方没有回复保活探测,您可以断言连接不能被视为有效,然后采取正确的行动.

This procedure is useful because if the other peers lose their connection (for example by rebooting) you will notice that the connection is broken, even if you don't have traffic on it. If the keepalive probes are not replied to by your peer, you can assert that the connection cannot be considered valid and then take the correct action.

这篇关于node.js 中的 setKeepAlive 如何工作以及如何实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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