• day36 作业


    客户端

    import struct
    import json
    from socket import *
    
    client=socket(AF_INET,SOCK_STREAM)
    # client.connect(('121.36.98.49',8822))
    client.connect(('127.0.0.1',8811))
    
    while True:
        cmd=input('请输入命令(dw or up +文件)>>:').strip()
        if len(cmd) == 0:continue
        client.send(cmd.encode('utf-8'))
    
        # 接收端
        # 1、先手4个字节,从中提取接下来要收的头的长度
        x=client.recv(4)
        print(x)
        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["file_size"]
    
        # 3、接收真实的数据
        recv_size = 0
        while recv_size < total_size:
            recv_data=client.recv(1024)
            recv_size+=len(recv_data)
            with open(f"my{header_dic['file_name']}",'wb') as f :
                f.write(recv_data)
        else:
            print()
    

    服务端

    import struct
    import json
    from socket import *
    
    
    server = socket(AF_INET, SOCK_STREAM)
    server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    server.bind(('127.0.0.1',8811))
    # server.bind(('0.0.0.0',8812))
    server.listen(5)
    
    while True:
        conn, client_addr = server.accept()
    
        while True:
            try:
                cmd = conn.recv(1024)
                if len(cmd) == 0: break
                cmd = cmd.decode('utf-8')
                cmd = cmd.split(',')
                print(cmd[0],cmd[1])
                if cmd[0] == 'up':
                    pass # 执行上传
                elif cmd[0] == 'dw': # 执行下载
                    print('开始传送')
                    with open(f'/hz/{cmd[1]}','rb') as f :
                        file_data = f.read()
                        print(file_data)
                        print('传送完毕')
                    file_size = len(file_data)
                    header_dic = {
                        "mode": cmd[0],
                        'file_name':cmd[1],
                        "file_size": file_size,
                    }
                    print(header_dic)
                    json_str = json.dumps(header_dic)
                    json_str_bytes = json_str.encode('utf-8')
                    x = struct.pack('i', len(json_str_bytes))
                    print(x)
                    conn.send(x)
                    conn.send(json_str_bytes)
                    conn.send(file_data)
    
    
            except Exception:
                break
        conn.close()
    
  • 相关阅读:
    CentOS7使用firewalld打开关闭防火墙与端口
    SELinux: Could not downgrade policy file
    CentOS 安装 semanage 命令
    漏洞: RHSA2017:3075: wget security update
    CentOS7增加或修改SSH端口号
    gnl's not lao 道德经 英文版
    当代 IT 大牛排行榜
    当代 IT 大牛排行榜
    2008 年个人回忆与总结
    Patch2 for NetBeans IDE 6.5 Now Available
  • 原文地址:https://www.cnblogs.com/hz2lxt/p/12752995.html
Copyright © 2020-2023  润新知