Python-simple simulation client uploading data

department

Server

from socket import *

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:
        a = conn.recv(4)
        try:
            if a:
                header_size = struct.unpack('i', a)[0]
                header_json_bytes = conn.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 = conn.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()
                        break
                else:
                    print('文件损坏')
                    break
            else:
                print('文件不存在或格式有误')
                break
        except Exception:
            print('错误 请输入正确文件路径')

Client

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

client = socket(AF_INET, SOCK_STREAM)
client.connect(('127.0.0.1', 8080))

while True:
    file_path = input('请输入文件路径:').strip()
    if len(file_path) == 0:
        continue
    if os.path.exists(file_path):
        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')
        client.send(struct.pack('i', len(header_json_bytes)))
        print('发送报头长度')
        client.send(header_json_bytes)
        print('发送报头内容')
        with open(f'{file_path}', 'rb') as f:
            for i in f:
                client.send(i)
            print('文件已发出')

    else:
        print('文件不存在')

Guess you like

Origin blog.csdn.net/msmso/article/details/108013564