Import socket DEF main (): # create socket TCP_SOCKET = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # get server Port ip dest_addr the INPUT = ( " Please enter the server's ip: " ) dest_port = int (the INPUT ( " Please enter the server's Port: " )) # linked server tcp_socket.connect ((dest_addr, dest_port)) # get the download file name file = the iNPUT ( " Please enter the name of the file to be downloaded: " ) # the file name of the sender to the server tcp_socket.send (file.encode ( " GBK " )) #Receiving file data recv_data = tcp_socket.recv (1024 ) # save the received data to a file IF recv_data: with Open ( " copy " + File, " WB " ) AS F: f.write (recv_data) # Close sockets tcp_socket.close () IF __name__ == " __main__ " : main ()
Import Socket DEF send_file_2_client (client_socket, client_addr): # . 1 receiving the downloaded file name # reception request transmitted to the client, the receiving client sent, the file name file_name = client_socket.recv (1024 ) Print ( " client% s sent, file name: S% " % (STR (client_addr), file_name.decode ( " GBK " ))) FILE_CONTENT = None # 2 to open the file, read data the try : F = open (file_name.decode ( " GBK " ), " rb " ) FILE_CONTENT =f.read () f.close () the except Exception AS RET: Print ( " do not want to download the file S% " % RET) # Data 3 to send the file to the client IF FILE_CONTENT: # echo part of the data to the client client_socket. the send (FILE_CONTENT) DEF main (): # buy a cell phone - create tcp socket TCP_SOCKET = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # into the phone card - binding tcp_socket.bind (( "" , 7890 ) ) # set the phone to ring the normal mode (the default socket so that by the active becomes passive and the listen) tcp_socket.listen (128 ) the whileTrue: # wait for the arrival of someone else's phone (waiting for a client link the Accept) client_socket, client_addr = tcp_socket.accept () # Print (client_socket) Print (client_addr) send_file_2_client (client_socket, client_addr) # close the socket client_socket.close () TCP_SOCKET .close () IF __name__ == " __main__ " : main ()