day37 homework

Server 

import socket
 import struct
 import json
 import os 


server = socket.socket (socket.AF_INET, socket.SOCK_STREAM) 

server.bind (( ' 172.0.0.1 ' , 8080 )) 

server.listen ( 5 ) 

while True: 
    conn, client_addr = server.accept () 

    the while True:
         the try : 

            file = conn.recv (1024 )
             if len (file) == 0:
                 BREAK 

            # presence or absence of the downloaded file to determine 
            if not os.path.exists (File): 
                conn.send ( ' download link does not exist ' .encode ( ' GBK ' ))
                 BREAK 

            # Open the file to read data 
            with Open (File, ' rb ' ) AS f: 
                RES = f .read () 

                res_len = len (RES) 

            # production head 
            header_dic = { " total_size " : res_len} 

            json_str = json.dumps (header_dic) 
            json_str_bytes = json_str.encode ( 'GBK ' ) 

            # transmit header length 
            X = struct.pack ( ' I ' , len (json_str_bytes)) 
            conn.send (X) 

            # data transmission header 
            conn.send (json_str_bytes) 

            conn.send (RES) 
        the except Exception:
             BREAK 
    conn.close () 



client 

import socket
 import json
 import struct 


client = socket.socket (socket.AF_INET, socket.SOCK_STREAM) 

client.connect (( ' 172.0.0.1 ' , 8080 )) 

while  True:
    fileThe INPUT = ( ' Please enter the name of the file you want to download ' ) .strip () 

    IF len (File) == 0:
         the Continue 

    client.send (file.encode ( ' GBK ' )) 

    # first to receive a 4, was prepared to give the length of the header information 
    X = client.recv (. 4 ) 
    header_len = struct.unpack ( ' I ' , X) [0] 

    # , after the head has a length, the length of the header information total_size get inside 
    json_str_bytes = client.recv (header_len) 
    json_str = json_str_bytes.decode ( ' gbk ' ) 
    header_dic =  json.loads (json_str)
    total_size = header_dic ["total_size"]

    recv_size = 0
    while total_size > recv_size:
        recv_data = client.recv(1024)
        recv_size += len(recv_data)
        print(recv_data.decode('gbk'), end='')
    print()

 

Guess you like

Origin www.cnblogs.com/yding/p/12749026.html