Advertisement
DrAungWinHtut

fileclient5.py

Feb 2nd, 2024
911
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.03 KB | None | 0 0
  1. import socket
  2. import os
  3.  
  4. def receive_data(sock):
  5.     try:
  6.         data = sock.recv(1024).decode('utf-8')
  7.         return data
  8.     except UnicodeDecodeError:
  9.         # Handle binary data
  10.         return sock.recv(1024)
  11.  
  12. def download_file(server_socket, filename):
  13.     with open(filename, 'wb') as f:
  14.         while True:
  15.             data = server_socket.recv(1024)
  16.             if not data:
  17.                 break
  18.             f.write(data)
  19.  
  20. def main():
  21.     host = "s3.greenhackers.org"
  22.     port = 5001
  23.  
  24.     s = socket.socket()
  25.     s.connect((host, port))
  26.  
  27.     # 1. Receive the file list from the server
  28.     files_list = receive_data(s)
  29.     print("Available Files:")
  30.     print(files_list)
  31.  
  32.     # 2. Select a file to download
  33.     selected_file = input("Enter the filename to download: ")
  34.     s.send(selected_file.encode())
  35.  
  36.     # 3. Receive the file from the server
  37.     download_file(s, selected_file)
  38.  
  39.     print(f"\nFile {selected_file} downloaded successfully.")
  40.  
  41.     s.close()
  42.  
  43. if __name__ == "__main__":
  44.     main()
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement