码迷,mamicode.com
首页 > 其他好文 > 详细

No.4 文件断点续传(Client)

时间:2019-07-30 18:50:44      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:pytho   day   写入   val   sts   upd   json   result   length   

import socket, json, struct, hashlib, os, shutil
codes = {
    "文件已存在":1001,
    "文件不存在":1002
}
‘‘‘
后开始
1.接收字典的长度;
2.利用字典的长度来接收字典(FileName,File_md5值,FileSize)
3.利用File_md5值判断需下载的文件是否存在。(若存在,则需要续传)
4.若文件已存在发送字典(Code,FileSize)
若文件不存在发送字典(Code,FileSize(0))
5.若文件已存在,接收文件.并且续写进文件中.
若文件不存在,接收文件.并且写入文件中.
7.校验完整性
8.将md5的值改成FileName
‘‘‘
File_path = rE:\Python\OldBoy\Mycode\Day3\FTP断点续传\dengfei\Home # 下载至
client = socket.socket()
client.connect(("127.0.0.1",8080,))

def handle(client):
    File_info_lenth = struct.unpack("i",client.recv(4))[0]
    File_info = json.loads(client.recv(File_info_lenth).decode("utf-8"))

    FileName = File_info["FileName"]
    FileSize = File_info["FileSize"]
    md5_val = File_info["md5_val"]

    Md5_Path = os.path.join(File_path,md5_val)
    FileName_path = os.path.join(File_path,FileName)
    if os.path.exists(Md5_Path):
        Md5_Size = os.path.getsize(Md5_Path)
    else:
        Md5_Size = 0
    response = {
            "Code":None,
            "Md5_Size":None
        }
    if os.path.exists(Md5_Path): 
        response["Code"] = 1001
        response["Md5_Size"]  = Md5_Size
    else:
        response["Code"] = 1002
        response["Md5_Size"] = 0

    client.send(json.dumps(response).encode("utf-8"))
    
    client.send(recevie(Md5_Path,Md5_Size,FileSize).encode("utf-8"))

    result = client.recv(1024)

    if result == b200:
        shutil.move(Md5_Path,FileName_path)
        print("文件完整!")
        
    elif result == b404:
        print("文件异常!")
    else:
        print("未知错误!")

def recevie(Md5_Path,Md5_Size,FileSize):
    recevie_data = 0
    recevie_length = Md5_Size
    md5 = hashlib.md5()
    with open(Md5_Path, ab) as f:
        while recevie_length < FileSize:
            data = client.recv(1024)
            f.write(data)
            recevie_length += len(data)
            md5.update(data)
            val = int(recevie_length / FileSize * 100)
            print(\r%s%%|%s % (val, "#" * val,), end=‘‘)
    print("")

    return md5.hexdigest()

def run(client):
    handle(client)

run(client)

 

No.4 文件断点续传(Client)

标签:pytho   day   写入   val   sts   upd   json   result   length   

原文地址:https://www.cnblogs.com/deng-fei/p/11271934.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!