TCP的三次握手和四次挥手

Posted sayiqiu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TCP的三次握手和四次挥手相关的知识,希望对你有一定的参考价值。

采用两次握手,那么若Client向Server发起的包A1如果在传输链路上遇到的故障,导致传输到Server的时间相当滞后,在这个时间段由于Client没有收到Server的对于包A1的确认,那么就会重传一个包A2,假设服务器正常收到了A2的包,然后返回确认B2包。由于没有第三次握手,这个时候Client和Server已经建立连接了。再假设A1包随后在链路中传到了Server,这个时候Server又会返回B1包确认,但是由于Client已经清除了A1包,所以Client会丢弃掉这个确认包,但是Server会保持这个相当于“僵尸”的连接。
所以采用两次握手,有可能会浪费Server的网络资源。

#coding:utf-8
from socket import *
import time
serverSocket = socket(AF_INET, SOCK_STREAM)
PORT = 8889  #选用的端口号
server_name = "uestc_crs/0.1" #服务器名称和版本号
serverSocket.bind((‘‘, PORT))
serverSocket.listen(5)
while 1:
    print("The webserver is ready to receive")
    connectionSocket, addr = serverSocket.accept()
    try:
        message = connectionSocket.recv(2048)
        filename = message.split()[1].decode() #提取请求报文中的请求对象
        print(filename)#测试得到的请求对象的文件名
        f = open(filename[1:],rb)#以二进制形式打开文件
        outputdata = f.read() #读取服务器上的文件内容
        #发送响应报文首部
        response = ‘‘‘
HTTP/1.1 200 OK
Connection: close
Date: %s
Server: %s
Conten-Length: %s
Content-Type: text/html

‘‘‘%(
    time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime()),
    server_name,
    len(outputdata)
    )
        #发送文件,按字节传输
        connectionSocket.send(response.encode())
        connectionSocket.send(outputdata) #一次性将报文实体发送到客户端(浏览器)
        connectionSocket.close()
        
    #请求对象不存在或路径错误时的响应
    except:  #put all possible errors in one case
        print("404 not found")
        response = ‘‘‘
HTTP/1.1 404 Not Found
Connection: close
Date: %s
Server: %s

<h1>File Not Found!</h1>
‘‘‘%(
    time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime()),
    server_name
    )
        connectionSocket.send(response.encode())
        connectionSocket.close()
serverSocket.close()

 


以上是关于TCP的三次握手和四次挥手的主要内容,如果未能解决你的问题,请参考以下文章

关于TCP的三次握手和四次挥手及其衍生问题

图解TCP的三次握手和四次挥手(简单明了)

TCP的三次握手和四次挥手

图解TCP的三次握手和四次挥手

图解TCP的三次握手和四次挥手

揭秘——TCP的三次握手和四次挥手