net.Dialer#KeepAlive 和 http.Transport#IdleTimeout 有什么区别?

kon*_*huo -2 network-programming http go

type Dialer struct {
    ......
    // KeepAlive specifies the keep-alive period for an active
    // network connection.
    // If zero, keep-alives are enabled if supported by the protocol
    // and operating system. Network protocols or operating systems
    // that do not support keep-alives ignore this field.
    // If negative, keep-alives are disabled.
    KeepAlive time.Duration
}
Run Code Online (Sandbox Code Playgroud)
type Transport struct {
    ......
// IdleConnTimeout is the maximum amount of time an idle
    // (keep-alive) connection will remain idle before closing
    // itself.
    // Zero means no limit.
    IdleConnTimeout time.Duration
}
Run Code Online (Sandbox Code Playgroud)

我认为keep-alive是tcp连接应该保持的时间。但 IdleConnTimeout 似乎是同一件事。那么它们之间有什么区别,如果我都设置了这些变量,tcp连接可以保持多长时间?

Cer*_*món 5

“保持活动”一词在两种情况下含义不同。

net/http 传输文档使用该术语来指代持久连接。保持活动连接或持久连接是一种可用于多个 HTTP 事务的连接。

Transport.IdleConnTimeout字段指定传输在关闭连接之前将未使用的连接保留在池中的时间。

Net Dialer 文档使用“保持活动”术语来指代用于探测连接运行状况的 TCP 功能

Dialer.KeepAlive字段指定向对等方发送 TCP 保持活动探测的频率。

这两个设置在堆栈的不同层执行不同的操作。