server------------------
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2018/6/7 8:41
# @File : 服务端.py
import socket
import os
import json
import struct
shar_dir = r'D:pytharmjichuyufamodel3practice2上传下载servershare'
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.bind(('127.0.0.1', 9909))
phone.listen(5)
print('starting...')
while True:
conn,client_addr = phone.accept()
print(client_addr)
while True:
try:
# 1收命令
res = conn.recv(8096) # b'get a.txt'
if not res:break
# 2,解析命令,提取相应命令参数
cmds = res.decode('utf-8').split() # ['get',filename]
filename = cmds[1]
# 3,易读的方式打开文件,读取文件内容发送给客户端
header_dic = {
'filename': filename,
'md5':'xxxdxxx',
'file_size': os.path.getsize(r'%s/%s' % (shar_dir, filename))
}
header_json = json.dumps(header_dic)
header_bytes = header_json.encode('utf-8')
# 2,先发送报头的长度
conn.send(struct.pack('i', len(header_bytes)))
# 3,再发报头
conn.send(header_bytes)
# 4,再发送真实的数据
with open('%s/%s' % (shar_dir, filename), 'rb') as f:
# conn.send(f.read())
for line in f:
conn.send(line)
except ConnectionResetError:
break
conn.close()
phone.close()
client-------------------------------------
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2018/6/7 8:41
# @File : 客户端.py
import socket
import struct
import json
dow_dir = r'D:pytharmjichuyufamodel3practice2上传下载clientdownload'
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.connect(('127.0.0.1', 9909))
while True:
# 1,发命令
cmd = input('>>:').strip()
if not cmd:continue
phone.send(cmd.encode('utf-8'))
# 2,以写的方式打开一个新文件
# 2.1收报头长度
obj = phone.recv(4)
header_size = struct.unpack('i', obj)[0]
# 2.2收报头
header_bytes = phone.recv(header_size)
# 从报头中解析出对真实数据的描述信息
header_json = header_bytes.decode('utf-8')
header_dic = json.loads(header_json)
print(header_dic)
total_size = header_dic['file_size']
filename = header_dic['filename']
# 2.4,接收真实的数据
with open('%s/%s' % (dow_dir, filename), 'wb') as f: # 服务端打开读方式,这里这种wb方式容易卡主
recv_size = 0
while recv_size < total_size:
line = phone.recv(1024)
f.write(line)
recv_size += len(line)
print('总大小:%s 已下载大小: %s' % (total_size, recv_size))
phone.close()