def receive1(client):
"真正的数据接收"
while True:
res = b""
res = res + client.recv(1024)
return res
def receive(client,filename):
"接收处理"
m = hashlib.md5()
rece_res_size = int(client.recv(1024).decode()) # 接收的结果长度,转成int型
client.send(b"1")
rece_size = 0
res = b""
filename = filename.decode()
f = open(filename + ".new","wb")
while rece_size < rece_res_size:
if rece_res_size - rece_size >1024: # 如果不是最后一次接收数据
size = 1024
else: # 最后一次接收数据
size = rece_res_size - rece_size
a = client.recv(size) # 循环接收数据
res = res + a
rece_size = len(res)
m.update(a)
f.write(a)
print("发送数据量:{0},接收数据量:{1}".format(rece_res_size,rece_size))
else:
serves_md5 = client.recv(1024).decode()
print("服务器MD5:",serves_md5)
print("客户端MD5:",m.hexdigest())
if serves_md5 == m.hexdigest():
print("文件接收并校验完毕!")
res.decode()
f.close()
def main():
client = socket.socket()
try:
client.connect(("localhost", 5000))
while True:
filename = input("请输入需要的文件名").strip().encode(encoding="utf-8")
if len(filename) == 0:
print("输入为空,重新输入")
continue
client.send(filename)
is_file = client.recv(1024)
if is_file == b"01":
client.send(b"OK")
receive(client,filename) # 调用函数接收数据,返回结果res(bytes)
else:
print(" {0} 文件不存在!".format(filename.decode()))
except ConnectionRefusedError:
print("等待服务器开机")
client.close()
main()
socketserver
什么是socketserver?为什么需要它呢?