Download fact, need two models, one is the server side, as a response and send data, the other model is the client side, initiate a download request and download data sent by the server, with this concept you can basically write.
1, the client-side code is
Import socket DEF main (): # create socket TCP_SOCKET = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # socket creates a socket, DGRAM as UDP, STREAM to TCP # input you want to bind the server information dest_ip = the iNPUT ( " Please enter the server ip: " ) dest_port = int (the iNPUT ( " Please enter the server Porti: " )) # bind server tcp_socket.connect ((dest_ip, dest_port)) # TCP server IP port need to bind this point need to distinguish between UDP and # need to download the input file name file_name = the iNPUT ( " Please enter the name of the file you want to download: " ) tcp_socket.send (file_name.encode ( ' UTF-8 ')) # Receive and download information Data tcp_socket.recv = (1024 * 1024 ) with Open ( ' new ' + file_name, ' WB ' ) AS F: f.write (Data) # close the socket tcp_socket.close () IF the __name__ == ' __main__ ' : main ()
2, server code
Import socket DEF main (): # create socket TCP_SOCKET = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # bind the local information LOCAL_ADDR = ( '' , 8080 ) tcp_socket.bind (LOCAL_ADDR) # monitor tcp_socket.listen (128 ) the TCP server has a listening #, wait for a connection link # download service new_client, client_addr = tcp_socket.accept () # wait connecting links, if the client connect a return tuples, tuples [0] is the next send and receive information the new socket is used, the ancestral [1] is connected to a client address file_name = new_client.recv (1024) .decode ( ' UTF-. 8 ' ) Print ( ' successful link from% s' %(str(client_addr))) try: f = open(file_name,'rb') data = f.read() except Exception as t: print("文件名错误%s" %(t)) new_client.send(data) new_client.close() tcp_socket.close() if __name__ == "__main__": main()
The above code, running directly on the two terminals can be linux