客户端:
import socket
import os
import struct
import json
client = socket.socket()
client.connect(('127.0.0.1',8085))
print('start....')
while True:
BASE_PATH = r'F:\1新建文件夹\新建文件夹'
movie_list = os.listdir(BASE_PATH)
print('请选择下列电影进行上传:')
for ind,movie in enumerate(movie_list,1):
print(ind,movie)
choice_index = int(input('请输入你想要上传的电影序号:').strip())
movie_name = movie_list[choice_index-1]
filename = os.path.join(BASE_PATH,movie_name)
movie_size = os.path.getsize(filename)
d = {'name':movie_name,'file_size':movie_size}
json_d = json.dumps(d)
json_d_bytes = json_d.encode('utf-8')
header = struct.pack('i',len(json_d))
client.send(header)
client.send(json_d_bytes)
with open(filename,'rb') as fr:
for line in fr:
client.send(line)
# client.close()
res = client.recv(1024)
print(res.decode('utf-8'))
服务端
import socket
import struct
import json
import os
server = socket.socket()
server.bind(('127.0.0.1',8085))
server.listen(5)
while True:
conn,addr = server.accept()
while True:
try:
header_bytes = conn.recv(4)
dict_len = struct.unpack('i',header_bytes)[0]
dict_bytes = conn.recv(dict_len)
dict_data = json.loads(dict_bytes.decode('utf-8'))
name = dict_data.get('name')
file_size = dict_data.get('file_size')
if not os.path.exists('datas'):
os.mkdir('datas')
filename = os.path.join('datas',name)
recv_data = 0
while recv_data < file_size:
data = conn.recv(1024)
recv_data += len(data) # data数据是一个二进制字节的数据,所以len(data)的长度就是这个数据的字节。
with open(filename,'ab') as fw:
fw.write(data)
fw.flush()
conn.send('上传完成'.encode('utf-8'))
except ConnectionResetError:
break
conn.close()