A TCP-based download
Client:
from socket import * import os def main(): tcp_socket = socket(AF_INET, SOCK_STREAM) #Create a socket tcp_ip = input( " Please input ip: " ) tcp_port = int(input( " Please enter the port: " )) #Receive the ip and port of the server with the input tcp_socket.connect((tcp_ip, tcp_port)) #Connect to the server file_name = input( " Please enter the name of the file to download: " ) #Enter the file name to be downloaded tcp_socket.send(file_name.encode()) #Send the file name to the server new_file = open(file_name, " wb " ) #Create an empty file time = 0 #Used for calculation read The number of bytes to take while True: mes = tcp_socket.recv(1024) #Receive the content returned by the server if mes: #If the content is not empty, execute new_file.write(mes.decode()) #Decode and write to the file time += len(mes) #Calculate bytes else : if time == 0: #If the number of bytes is empty, no content is received new_file.close() #Close the file os.remove (file_name) #Delete the file just created print ( " Nothing you want Downloaded file " ) else : print ( "The file was downloaded successfully" ) #If the time has a value, the name file transfer is completed break tcp_socket.close() #Close the socket if __name__ == ' __main__ ' : main()
Server:
import socket def file_deal(file_name): #Define a function to process the file the user asks to download try : files = open(file_name, " rb " ) # binary read mes = files.read() except : print ( " No such file " ) else : files.close() return mes def main(): tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create a socket tcp_socket.bind(( "" ,8080)) #Fixed port number tcp_socket.listen(128) #Convert active socket to passive socket Connect, listen to the connected client while True: client_socket,client_addr = tcp_socket.accept() #Use accept to get the sub-socket and the address of the client file_name = client_socket.recv(4096) #Receive data from the client mes = file_deal(file_name) #Call the function to process the file downloaded by the user if mes : #If the file is not empty send client_socket.send(mes) client_socket.close() #Close the sub-socket if __name__ == " __main__ " : main()