TCP "Connection" 是如何维护的,HTTP Keep-Alive 是如何影响它的?

How is a TCP "Connection" maintained, and how does HTTP Keep-Alive affect it?

我是一名应用程序开发人员,希望更多地了解这些年来我一直在提出的请求的传输层。我也一直在学习更多后端知识,并正在使用 websockets 构建我自己的实时数据服务,这让我很好奇数据实际上是如何移动的。

因此我了解了 TCP,也了解它的工作原理,但仍然有一个术语让我感到困惑 -- "TCP Connection"。我到处都看到它,实际上有一个线程打开了完全相同的问题......但正如 OP 在评论中所说的那样,实际上没有人回答这个问题: TCP vs UDP - What is a TCP connection?

"when we say that there is a connection established between two hosts, what does that mean? If I could get a magic microscope and inspect the server or the client, and - a-ha! - find the connection, what would I be looking at? Some variable allocated by the OS code? Some entry in some kind of table? How and when does that gets there, and how and when it is removed from there"

我一直在阅读以尝试自己解决这个问题,
这是一个很好的资源,详细介绍了 HTTP 流程,还提到了 "TCP Connection" https://blog.catchpoint.com/2010/09/17/anatomyhttp/

这是另一个关于 HTTP Keep-alive 的帖子,同样 "TCP Connection":


我的理解:
当客户端需要来自服务器的数据时,SYN/ACK 握手发生,此 "connection" 建立,双方就起始序列号、最大数据包大小等达成一致。

只要此 "connection" 仍然打开,客户端就可以 request/receive 数据而无需再次握手。 TCP Keep-alive 发送心跳以保持此 "connection" 打开

1) 不知何故 HTTP Header "Keep-alive" 也保持此 TCP "connection" 打开,即使 HTTP headers 是数据包有效载荷的一部分而且 TCP 层解析 HTTP headers?

似乎没有意义

对我来说,字面意义上的两台机器之间的 "connection" 似乎永远无法关闭,因为客户端总是可以自由地使用数据包访问服务器(例如第一个 SYN 数据包)

2) TCP "connection" 只是客户端和服务器从对方的IP 地址保存序列号吗?也许它只是一面写着 "hey this client is cool, accept messages from them without a handshake" 的旗帜?那么关闭连接是否只是将数据从内存中清除?

... both parties agree on the starting sequence number

不,他们不"agree"一个号码。每个方向都有自己的顺序编号。因此,客户端在 SYN 中向服务器发送从客户端到服务器的数据的初始序列号 (ISN),服务器在其 SYN 中发送从服务器到客户端的数据的 ISN。

Somehow a HTTP Header "Keep-alive" also keeps this TCP "connection" open ...

不是真的。使用 HTTP keep-alive,客户端只是很好地请求服务器在发送 HTTP 响应后不要关闭连接,以便可以使用相同的 TCP 连接发送另一个 HTTP 请求。服务器可能会决定是否遵循客户端的意愿。

To me it seems like a "connection" between two machines in the literal sense can never be closed,

每一方都可以发送一个带有 FIN 标志的数据包,以表示它将不再发送任何数据。如果双方都发送了 FIN,则连接被认为是关闭的,因为没有人会发送任何东西,因此也不会收到任何东西。如果一方决定不想再接收任何数据,它可以发送一个带有 RST 标志的数据包。

Is a TCP "connection" just the client and server saving the sequence number from the other's IP address?

有点。每一方都保存连接的当前 state,即涉及的 IP 和端口、当前预期的接收序列号、当前发送序列号、尚未确认的未完成字节......如果没有这样的状态(例如一个站点崩溃)则没有连接。

... maybe it's just a flag that's saying "hey this client is cool, accept messages from them without a handshake"

如果收到符合现有状态的数据包,则将其视为连接的一部分,即,将对其进行处理并更新状态。

So would closing a connection just be wiping that data out from memory?

关闭是告诉对方不再发送数据(使用 FIN),如果双方都完成了,则基本上都可以删除状态,然后就不再有连接了。