socket.setKeepAlive()
启用/禁用保持连接功能,并可选择配置保持连接探测时间。返回套接字本身。
🌐 Enable/disable keep-alive functionality, and optionally configure the keepalive probe timing. Returns the socket itself.
可能的语法有:
🌐 Possible signatures:
启用保持连接会设置在空闲套接字上发送第一个保持活动探测的初始延迟。
🌐 Enabling keep-alive sets the initial delay before the first keepalive probe is sent on an idle socket.
设置 initialDelay(以毫秒为单位)以设置从接收到最后一个数据包到第一次保持活动探测之间的延迟时间。将 initialDelay 设置为 0 将保持默认(或之前)设置值不变。
🌐 Set initialDelay (in milliseconds) to set the delay between the last
data packet received and the first keepalive probe. Setting 0 for
initialDelay will leave the value unchanged from the default
(or previous) setting.
将 interval(以毫秒为单位)设置为在连续的保持连接探测开始后 (TCP_KEEPINTVL) 之间的延迟。将 count 设置为在断开连接前发送的未确认探测的次数 (TCP_KEEPCNT)。两者仅在启用保持连接时生效。省略 interval 或 count 时,会使用默认值 1000 毫秒和 10。与 initialDelay 一样,非正的 interval 或 count 会保持相应的系统默认值不变。
🌐 Set interval (in milliseconds) to set the delay between successive
keepalive probes once they begin (TCP_KEEPINTVL). Set count to the
number of unacknowledged probes sent before the connection is dropped
(TCP_KEEPCNT). Both are only applied when keep-alive is enabled.
Omitting interval or count uses the defaults of 1000 ms and 10.
As with initialDelay, a non-positive interval or count leaves the
corresponding system default unchanged.
initialDelay 和 interval 是以毫秒为单位指定的,但底层的套接字选项是以整秒配置的;这些值会先除以 1000,然后向下取整后再应用。
启用保持活动功能将设置以下套接字选项:
🌐 Enabling the keep-alive functionality will set the following socket options:
SO_KEEPALIVE=1TCP_KEEPIDLE=initialDelay / 1000TCP_KEEPCNT=countTCP_KEEPINTVL=interval / 1000
在早于 1709 版本的 Windows 上,保持连接是通过 SIO_KEEPALIVE_VALS 配置的,它没有 probe-count 字段,所以在这些平台上 count 会被忽略。
🌐 On Windows versions older than build 1709, keep-alive is configured through
SIO_KEEPALIVE_VALS, which has no probe-count field, so count is ignored on
those platforms.