day31

粘包

"""
半连接:客户端给服务器发送一次握手信息,服务器回复确认后,
进入等待状态,但是客户端没有回应第三次握手信息,服务器会保存着客户端的
一些信息一直等待

洪水攻击:黑客通过不断的向服务器发送链接请求,但是不确认第三次信息,服务器出现大量的
time_wait状态,资源耗尽正常客户无法享受服务

为什么要先把报头长度传过来?????
因为粘包
"""

服务器

import socket
import struct
import os
import json

tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpSocket.bind(('127.0.0.1', 1688))
tcpSocket.listen()
while True:
   client_socket, data = tcpSocket.accept()
   f = None
   try:
       file_path = r'C:UsersmaoyuxianshenVideosCaptures4.粘包问题.mp4'
       file_size = os.path.getsize(file_path)
       file_info = {'file_name': '4.粘包问题.mp4', 'file_size': file_size}
       json_str = json.dumps(file_info).encode('utf-8')

       client_socket.send(struct.pack('q',len(json_str)))
       client_socket.send(json_str)
       f = open(file_path,'rb')

       while True:
           temp_data = f.read(2048)
           if not temp_data:
               break
           client_socket.send(temp_data)
       client_socket.close()
   except ConnectionResetError as e:
       print('出错了:', e)
   finally:
       if f:f.close()

客户端

import socket
import json
import struct

client = socket.socket()

try:
   client.connect(('127.0.0.1', 1688))
   head_size = struct.unpack('q',client.recv(8))[0]
   head_str = client.recv(head_size).decode('utf-8')
   file_info = json.loads(head_str)
   file_name = file_info.get('file_name')
   file_size = file_info.get('file_size')
   print('前期处理.......')

   recv_size = 0
   buffer_size = 2048
   f = open(file_name,'wb')
   while True:
       if file_size - recv_size >= buffer_size:
           temp_data = client.recv(buffer_size)
       else:
           temp_data = client.recv(file_size)
       f.write(temp_data)
       recv_size += len(temp_data)
       if recv_size == file_size:
           break
   f.close()
   client.close()
except ConnectionRefusedError as e:
   print('服务器链接失败', e)
except ConnectionResetError as e:
   print('服务器终断', e)

原文地址:https://www.cnblogs.com/zhuqihui/p/10946593.html