Client
Import OS Import Socket Import struct Import JSON Client = socket.socket () the client.connect (( ' 127.0.0.1 ' , 8080 )) the while True: movie_dir = R & lt ' F.: \ day31 \ video ' movie_list = the os.listdir (movie_dir ) for index, i in the enumerate (movie_list, 1 ): Print (index, i) choice = the iNPUT ( ' Please enter the number you want to select the movie: ' ) .strip () IF Not choice.isdigit (): Print ( ' Enter number ' ) Continue Choice = int (Choice) -. 1 IF Choice Not in Range (0, len (movie_list)): Print ( ' Please input the correct number ' ) Continue MOVIE_NAME = movie_list [Choice] movie_path = the os.path.join (movie_dir, MOVIE_NAME) # Get file size movie_size = os.path.getsize (movie_path) # production dictionary DIC = { ' name' : MOVIE_NAME, ' movie_size ' : movie_size} # create header json_dic = json.dumps (DIC) byte_dic = json_dic.encode ( ' UTF-. 8 ' ) header = struct.pack ( ' I ' , len (byte_dic)) # Send header client.send (header) # send dictionary client.send (byte_dic) # transmit real data with Open (movie_path, ' RB ' ) AS F: RES = f.readlines () for Iin res: client.send(i) print('xxx')
Server
Import Socket Import JSON Import struct Server = socket.socket () server.bind (( ' 127.0.0.1 ' , 8080 )) server.listen ( . 5 ) the while True: Conn, to addre = server.accept () the while True: the try : # receiving header dictionary header_dic conn.recv = (. 4 ) # parses the header length acquiring dictionary dic_size struct.unpack = ( ' I ' , header_dic) [0] Print(dic_size) # 接收字典 byte_dic = conn.recv(dic_size) dic = json.loads(byte_dic.decode('utf-8')) # 接收真实数据 real_size = dic.get('movie_size') recv_size = 0 while recv_size < real_size: data = conn.recv(1024) with open(r'D:\unloads\%s' % dic.get('name'), 'ab')as f: f.write(data) recv_size += len(data) print('ooo') except ConnectionResetError: break