网络下载作业

客户端

from socket import *
import json,struct

client = socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8080))
while True:  #输入例子get 1.png
    cmd = input('输入命令(cmd 文件名)').strip()
    if len(cmd) == 0: continue
    client.send(cmd.encode('utf-8'))
    # 接收端
    # 1、先手4个字节,从中提取接下来要收的头的长度
    x = client.recv(4)
    header_len = struct.unpack('i', x)[0]
    # 2、接收头,并解析
    json_str_bytes = client.recv(header_len)
    json_str = json_str_bytes.decode('utf-8')
    header_dic = json.loads(json_str)
    # print(header_dic)
    total_size = header_dic["total_size"]
    # 3、接收真实的数据
    recv_size = 0
    date = bytes()
    while recv_size < total_size:
        recv_data = client.recv(1024)
        recv_size += len(recv_data)
        date+=recv_data
    else:
        cmd, file_name = cmd.split(' ')      #路径自己定义
        path = r'D:/' + file_name
        with open(path, 'wb')as f:
            f.write(date)
            print('下载成功')

服务端

from socket import *
import json,os,struct

server = socket(AF_INET,SOCK_STREAM)
server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
server.bind(('127.0.0.1',8080))
server.listen(5)


def get_file(header_dic):
    with open(header_dic['path'],'rb')as f:
        date = f.read()
    return date



def create_head(file_name):
    header_dic = {
        "filename": None,
        "total_size": 0,
        'path':None
    }#路径自己定义
    path = r'C:/' + file_name
    if not os.path.exists(path):
        return False,'无此文件'
    header_dic['file_name'] = file_name
    header_dic['total_size'] = os.path.getsize(path)
    header_dic['path'] = path
    return True,header_dic

while True:
    conn,client_addr=server.accept()
    while True:
        try:
            res=conn.recv(1024).decode('utf-8')
            if len(res) == 0:break
            cmd,file_name = res.split(' ')
            print(cmd,file_name)
            if cmd == 'get':
                print(1)
                flag,header_dic = create_head(file_name)
                print(flag,header_dic)
                if flag:
                    date = get_file(header_dic)
                    json_str = json.dumps(header_dic)
                    json_str_bytes = json_str.encode('utf-8')
                    x = struct.pack('i', len(json_str_bytes))
                    conn.send(x)
                    conn.send(json_str_bytes)
                    conn.send(date)
        except Exception:
            break
    conn.close()

 

来源:https://www.cnblogs.com/bk134/p/12747571.html

标签