25

TCP为什么需要握手

 3 years ago
source link: http://www.cnblogs.com/Brake/p/13549939.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、TCP握手流程

baUfQfj.png!mobile

二、为什么不是4次握手

TCP的每次请求都是成对的,原则上应该是四次

  1. 【Client to Server】第一次SYN,seq=x
  2. 【Server to Client】 第二次ACK,seq=y,ack=x+1(没有携带数据的ACK不消耗序列号)
  3. 【Server to Client】 第三次SYN,seq=y,
  4. 【Client to Server】第四次ACK,seq=x+1,ack=y+1.

可以看出第二次和第三次都是 Server to Client ,且 他们之间没有任何事件发生 ,所以可以合并,不是四次的原因是2,3步骤合并,增加效率。

三、为什么需要握手(为什么需要三《 ”四“》 次握手)

要回答为什么先看看什么是TCP链接。ref https://tools.ietf.org/html/rfc793

    The reliability and flow control mechanisms described above requirez
    that TCPs initialize and maintain certain status information for
    each data stream.  The combination of this information, including
    sockets, sequence numbers, and window sizes, is called a connection.
    Each connection is uniquely specified by a pair of sockets
    identifying its two sides.

为了保证可靠性传输,TCP需要两边维护socket,序列号,和窗口大小(流量控制用),握手就是为了在数据开始传输前让客户端和服务器准确无误的交换上述信息。

需要握手的原因:

  1. 阻止已经失效的历史请求的初始化【谢希仁】
  2. 只有通过三次握手才能交换序列号

3.1 阻止已经失效的历史请求的初始化

ref: https://tools.ietf.org/html/rfc793

The principle reason for the three-way handshake is to 
prevent old duplicate connection initiations from causing confusion. 

假如只有两次握手

MraMVvv.png!mobile

假如服务端在ack以后就建立了链接,当有延迟的数据在 链接关闭后 到达服务端,

  • 服务端不知道这是旧链接,直接建立返回ack,且建立了链接。
  • 因为上一次链接已经关闭,客户端不认识这个ack,直接丢弃。

这样会导致服务端资源被这种失效的链接给浪费。

3.2 只有通过三次握手才能交换序列号

序列号是可靠性传输的根本,通过序列号,接收方可以去重,可以保证TCP流按照顺序最终被接受。

初始序列号是随机生成的(为了安全),所以在链接建立之初需要双方通过SYN来告知对方自己的初始序列号。

同时每一个发出去的序列号,都需要一个接收方的ACK,来告诉发送方:我已经收到了-- 可靠性保证

所以两次握手不行: 服务端的SYN,没有办法ACK。

由于第二次和第三次可以合并,所以最终把逻辑上的四次握手变成了三次。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK