基於TCP協議的大文件傳輸(粘包問題處理)

基於TCP的大文件上傳服務端實現

# 服務端
# -*- coding: utf-8 -*-

from socket import *
import json, struct

server = socket(AF_INET, SOCK_STREAM)
server.bind(('127.0.0.1', 8080))  # 本地循環地址
server.listen(5)

while True:
    # 連接循環  accept() -> (socket object, address info)
    conn, addr = server.accept()
    try:
        # 先接收報頭
        header = conn.recv(4)
        # 解析報頭獲取字典長度  unpack(fmt, buffer) -> (v1, v2, ...)
        header_len = struct.unpack('i', header)[0]
        # 獲取字典
        dic_bytes = conn.recv(header_len)
        dic_json = dic_bytes.decode('utf-8')
        dic = json.loads(dic_json)
        file_size = dic.get('file_size')
        file_name = dic.get('file_name')
        # 接收文件
        recv_size = 0
        with open(file_name, 'wb') as f:
            # 循環接收文件數據
            while recv_size < file_size:
                data = conn.recv(1024)
                f.write(data)  # 寫進文件
                recv_size += len(data)
        print(dic.get('msg'))
        conn.send('文件傳輸成功'.encode('utf-8'))
    except ConnectionResetError:
        break
#客戶端

# -*- coding: utf-8 -*-
import socket
import os
import json
import struct

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 8080))

# 文件大小和名字
file_size = os.path.getsize(r'E:測試視頻.mp4')  # 文件地址本身寫入
file_name = '性感荷官在線發牌.mp4'
# 定義一個字典
dic = {
    'file_size': file_size,
    'file_name': file_name,
    'msg': '注意身體喲'
}
dic_bytes = json.dumps(dic).encode()
# 製做字典報頭
dic_header = struct.pack('i', len(dic_bytes))
# 發送報頭
client.send(dic_header)
# 發送字典
client.send(dic_bytes)
# 發送文件
with open(r'E:測試視頻.mp4', 'rb') as f:
    for line in f:
        client.send(line)

data = client.recv(1024).decode('utf-8')
print(data)
相關文章
相關標籤/搜索