At work, I often need to download files or other data from the server, so I wrote a file download case using the tcp protocol:
1 Server code:
import socket import os if __name__ == "__main__": serves_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #socket绑定ip serves_socket.bind(("", 9080)) #socket监听 serves_socket.listen(128) #socket链接 while True: client_socket, client_address = serves_socket.accept() #接shou数据 recv_data = client_socket.recv(1024) recv_msg = recv_data.decode( "utf-8" ) print (recv_msg) #Find if the file exists if os.path.exists(recv_msg): #If the file exists on the desktop with open (recv_msg , "rb" ) as f: while True : file_content = f.read(1024) if file_content: client_socket.send(file_content) Else : break #If it does not exist, close the client client_socket.close() serves_socket.close ()#Life is too short, I use python
2 Client code:
import socket if __name__ == "__main__": client_socket = socket.socket(socket.AF_INET , socket.SOCK_STREAM) #Connected server client_socket.connect(( input ( "Please enter the ip address" ) , int ( input ( "Please enter the port number" )))) # Send to Search file name file_name = input ( "Please enter the file name to search for" ) fil_data = file_name.encode("utf-8") client_socket.send(fil_data) str_list = [] #Receive the returned data while True : recv_file_data = client_socket.recv(1024) if recv_file_data: str_list.append(recv_file_data) else: break #写入文件 if str_list: with open("../../" + file_name, "wb") as f: for file_content_b in str_list: f.write(file_content_b) else : print ( "The file you want to download does not exist" ) client_socket.close() Client execution result:
Please enter the ip address 192.168.243.130 Please enter port number 9080 Please enter the name of the file you are looking for 1.txt