zoukankan      html  css  js  c++  java
  • 网络下载作业

    客户端

    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()
  • 相关阅读:
    一款单机游戏应该有的一些要素
    终于成功注册了Amazon.com的Affiliate
    创办公司的步骤不完全讲解(二)
    继续新环境没有asp.net mvc3项目模板的问题
    在自己的博客上打个广告,Kinect for Windows要的来
    数据仓库走向灭亡??
    Oracle & Endeca
    无题
    无题
    【译著】第7章 SportsStore:一个真实的应用程序 — 《精通ASP.NET MVC 3框架》
  • 原文地址:https://www.cnblogs.com/bk134/p/12747571.html
Copyright © 2011-2022 走看看