Python-简单模拟从服务端下载数据

服务端

from socket import *
import os
import hashlib
import json
import struct

server = socket(AF_INET, SOCK_STREAM)
server.bind(('127.0.0.1', 8080))
server.listen(5)

while True:
    conn, client_addr = server.accept()
    print(conn, client_addr)
    print('接受链接请求')
    while True:
        try:
            msg = conn.recv(1024).decode('utf-8')
            cmd, file_path = msg.split()
            if os.path.exists(file_path) and cmd == 'get':
                with open(f'{file_path}', 'rb') as f:
                    md5 = hashlib.md5()
                    md5.update(f.read())

                header_dic = {
    
    'total_size': os.path.getsize(file_path),
                              'filename': os.path.basename(file_path),
                              'md5': md5.hexdigest()}

                header_json_bytes = json.dumps(header_dic).encode('utf-8')
                conn.send(struct.pack('i', len(header_json_bytes)))
                print('发送报头长度')
                conn.send(header_json_bytes)
                print('发送报头内容')
                with open(f'{file_path}', 'rb') as f:
                    for i in f:
                        conn.send(i)
                    print('文件已发出')


        except Exception as e:
            break
    conn.close()

server.close()

客户端

from socket import *
import hashlib
import json
import struct
# get F:\图片集\拉斯维尼.jpg
client = socket(AF_INET, SOCK_STREAM)
client.connect(('127.0.0.1', 8080))

while True:
    cmd = input('请输入文件名:').strip()
    if len(cmd) == 0:
        continue
    client.send(cmd.encode('utf-8'))
    a = client.recv(4)
    try:
        if a:
            header_size = struct.unpack('i', a)[0]
            header_json_bytes = client.recv(header_size)
            header_json = header_json_bytes.decode('utf-8')
            header_dic = json.loads(header_json)

            total_size = header_dic['total_size']
            filename = header_dic['filename']
            recv_size = 0
            file_content = b''
            while recv_size < total_size:
                date = client.recv(1024)
                recv_size += len(date)
                file_content += date
            mb5 = hashlib.md5()
            mb5.update(file_content)

            if mb5.hexdigest() == header_dic['md5']:
                with open(r'%s' % filename, 'wb') as f:
                    f.write(file_content)
                    print('下载成功')
                    f.flush()
            else:
                print('文件损坏')
        else:
            print('文件不存在或格式有误')
    except Exception:
        print('错误 请输入正确文件路径')

猜你喜欢

转载自blog.csdn.net/msmso/article/details/108013029