python 解决粘包问题的例子(ftp文件的上传与下载)简单版本

时间:2024-01-13 14:13:02

服务端

! /user/bin/env python3

-- coding:utf_8 --

"""
Author:Markli
# 2019/9/9,16:41
"""
import socketserver
import os, json,struct
if not os.path.isdir('ftp文件'):
os.mkdir("ftp文件")
file_list = os.listdir('ftp文件')
file_str = str(file_list)
class MyClass(socketserver.BaseRequestHandler):
def handle(self):
print(self)
while True:
# print(file_str)
try:
index = self.request.recv(1024).decode('utf-8')
print('请求为', index)
except:
break
if index == '1':
try:
while True:
head = self.request.recv(4)
head_json_len = struct.unpack('i', head)[0]
data = self.request.recv(head_json_len).decode('utf-8')
head_json = json.loads(data)
file_name = head_json['file_name']
print(file_name)
file_len = head_json['data_size']
count = 0
data_file = b''
while count < file_len:
if file_len < 1024:
data = self.request.recv(file_len)
else:
if file_len - count >= 1024:
data = self.request.recv(1024)
else:
data = self.request.recv(file_len - count)
data_file += data
count += len(data)
file_path = os.path.join('ftp文件', file_name)
with open(file_path, 'wb') as fw:
fw.write(data_file)
print(f"{self.client_address}上传{file_name}成功")
except:
break
elif index == '2':
try:
while True:
self.request.send(file_str.encode())
index = self.request.recv(4).decode()
index = int(index)
file_name = file_list[index]
file_path = os.path.join('ftp文件', file_list[index])
with open(file_path, 'rb') as f:
data = f.read()
headers = {'data_size': len(data), 'file_name': file_name}
head_json = json.dumps(headers)
head_json_bytes = bytes(head_json, encoding='utf-8')
self.request.send(struct.pack('i', len(head_json_bytes)))
self.request.send(head_json_bytes)
self.request.send(data)
except:
break
else:
continue
if name == 'main':
socket = socketserver.ThreadingTCPServer(('172.0.0.1',8080),MyClass)
socket.serve_forever()

客户端

! /user/bin/env python3

-- coding:utf_8 --

"""
Author:Markli
# 2019/9/9,16:41
"""

import socket
import os,struct,json
client = socket.socket()
client.connect(('172.0.0.1',8080))
func_dic = {
'1':'upper',
'2':'load'
}
if not os.path.isdir('my'):
os.mkdir('my')
file_list = os.listdir('my')

file_str = str(file_list)

while True:
for key, Value in func_dic.items():
print(key, Value)
choice_func = input("请选择你需要的功能")
client.send(choice_func.encode('utf-8'))
if choice_func == 'q':
break
# choice_func = int(choice_func)
# if func_dic.get(choice_func):
if choice_func == '1':
while True:
for index, file in enumerate(file_list):
print(index, file)
choice_file = input("请输入你要上传的文件编号")
choice_file = int(choice_file)
file_name = file_list[choice_file]
print(file_name)
file_path = os.path.join('my', file_name)
with open(file_path, 'rb') as fr:
data = fr.read()
headers = {'data_size': len(data), 'file_name': file_name}
print(headers['data_size'])
head_json = json.dumps(headers)
head_json_bytes = bytes(head_json, encoding='utf-8')
client.send(struct.pack('i', len(head_json_bytes)))
client.send(head_json_bytes)
client.send(data)
print(f"上传{file_name}成功")
if choice_func == '2':
while True:
choice_func = int(choice_func)
data = client.recv(1024).decode()
data = eval(data)
file_list = list(data)
for index, file in enumerate(file_list):
print(index, file)
choice = input("请选择你要下载的文件编号")
client.send(choice.encode())
head = client.recv(4)
head_json_len = struct.unpack('i', head)[0]
data = client.recv(head_json_len).decode('utf-8')
head_json = json.loads(data)
file_name = head_json['file_name']
file_len = head_json['data_size']
count = 0
data_file = b''
while count < file_len:
if file_len < 1024:
data = client.recv(file_len)
else:
if file_len - count >= 1024:
data = client.recv(1024)
else:
data = client.recv(file_len - count)
data_file += data
count += len(data)
file_name = os.path.join('my', file_name)
with open(file_name, 'wb') as fw:
fw.write(data_file)
print(f'{file_name}下载成功')
client.close()