zoukankan      html  css  js  c++  java
  • 模拟百度网盘中文件的上传与下载

    # 实现一个文件的上传或下载     server端
    # 配置文件 ip地址 端口
    import socket
    import struct
    import json
    sk = socket.socket()
    sk.bind(("127.0.0.1", 8090))
    sk.listen()
    
    buffer = 1024
    conn, addr = sk.accept()
    # 接收
    head_length = conn.recv(4)
    head_length = struct.unpack("i", head_length)[0]
    json_head = conn.recv(head_length).decode("utf-8")
    head = json.loads(json_head)   # 字典head
    file_size = head["filesize"]
    with open("music", "wb") as f:
        while file_size:
            if file_size >= buffer:
                content = conn.recv(buffer)
                f.write(content)
                file_size -= buffer
            else:
                content = conn.recv(file_size)
                f.write(content)
                break
    conn.close()
    sk.close()
    
    
    
    
    
    # 发送端(client)
    import socket
    import os
    import json
    import struct
    sk = socket.socket()
    sk.connect(("127.0.0.1", 8090))
    buffer = 1024
    # 发送文件
    head = {"filepath": r"C:Users26651Music", "filename": r"朱七 - 夏天已过去.mp3", "filesize": None}
    file_path = os.path.join(head["filepath"], head["filename"])   # 文件的路径
    file_size = os.path.getsize(file_path)  # 文件的大小
    head["filesize"] = file_size
    json_head = json.dumps(head)   # 从字典转成字符串
    byte_head = json_head.encode("utf-8")   # 从字符串转字节
    head_length = struct.pack("i", len(byte_head))   # 将报头的长度转化四个字节
    sk.send(head_length)
    sk.send(byte_head)
    with open(file_path, "rb") as f:
        while file_size:
            if file_size >= buffer:
                content = f.read(buffer)
                sk.send(content)
                file_size -= buffer
            else:
                content = f.read(file_size)
                sk.send(content)
                break
    sk.close()
  • 相关阅读:
    Appium+python自动化3-启动淘宝app
    Appium+python自动化2-环境搭建(下)
    Appium+python自动化1-环境搭建(上)
    postman提取返回值
    Android studio(AS)的下载和安装
    monkey的安装和配置
    配置自己的CentOS7服务器
    mac-homebrew安装太慢
    vue.js中祖孙通信之provide与inject
    nginx location 以及 proxy_pass 的几种情况 以/结尾的问题
  • 原文地址:https://www.cnblogs.com/nxrs/p/10481919.html
Copyright © 2011-2022 走看看