基于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)