下载文件要保证文件的完整性, 一般采用TCP协议进行两台主机间的socket通信

1 client.py

  1. from socket import *
  2. tcp_socket = socket(AF_INET, SOCK_STREAM)
  3. dest_ip = input("请输入下载服务器的ip:")
  4. dest_port = int(input("请输入服务器的port:"))
  5. tcp_socket.connect((dest_ip, dest_port))
  6. down_file = input("请输入下载的文件名字:")
  7. tcp_socket.send(down_file.encode("utf-8"))
  8. recv_data = tcp_socket.recv(1024)
  9. if recv_data:
  10. with open("[新]"+down_file, "wb") as f:
  11. f.write(recv_data)
  12. tcp_socket.close()

2 server.py

  1. from socket import *
  2. def send_file_to_client(client_socket, client_addr):
  3. # 接收客户端需要下载的文件名
  4. file_name = client_socket.recv(1024).decode("utf-8")
  5. print("客户端 {} 要下载的文件是:{}".format(client_addr, file_name))
  6. # 打开这个文件,读取数据
  7. file_content = None
  8. try:
  9. f = open(file_name, "rb") # 以二进制读取
  10. file_content = f.read()
  11. f.close()
  12. except Exception as ret:
  13. print("没有要下载的文件:{}".format(file_name))
  14. # 发送文件数据到客户端
  15. if file_content:
  16. client_socket.send(file_content)
  17. tcp_socket = socket(AF_INET, SOCK_STREAM)
  18. print("服务器绑定端口号:7890")
  19. tcp_socket.bind(("", 7890))
  20. print("令tcp_socket变为监听套接字")
  21. tcp_socket.listen()
  22. print("正在等待接收客户端的连接请求...")
  23. client_socket, client_addr = tcp_socket.accept()
  24. print("客户端信息:", client_addr)
  25. send_file_to_client(client_socket, client_addr)
  26. client_socket.close()
  27. tcp_socket.close()

image.png
image.png
image.png