Advertisement
DrAungWinHtut

fileserver5.py

Feb 2nd, 2024
735
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. import socket
  2. import os
  3. import threading  # Import the threading module
  4.  
  5. def handle_client(client_socket):
  6.     # 1. List all files in the current directory
  7.     files_list = list_files_in_current_dir()
  8.     files_str = "\n".join(files_list)
  9.    
  10.     # 2. Send the file list to the client
  11.     client_socket.send(files_str.encode())
  12.  
  13.     # 3. Receive the selected file name from the client
  14.     filename = client_socket.recv(1024).decode()
  15.     print(f"\nSelected file: {filename}")
  16.  
  17.     if not os.path.exists(filename):
  18.         print('No such file in Server!, exiting.....')
  19.         client_socket.close()
  20.         return
  21.  
  22.     # File exists in the server, transferring now...
  23.     print('File exists in Server, Transferring now...')
  24.  
  25.     with open(filename, 'rb') as f:
  26.         for byte in f:
  27.             client_socket.send(byte)
  28.  
  29.     print(f'\n\nTotal File Size is {os.path.getsize(filename)} bytes')
  30.     print('File transferred')
  31.  
  32.     client_socket.close()
  33.  
  34. def list_files_in_current_dir():
  35.     current_dir = os.getcwd()
  36.     files = [f for f in os.listdir(current_dir) if os.path.isfile(os.path.join(current_dir, f))]
  37.     return files
  38.  
  39. host = "s3.greenhackers.org"
  40. port = 5001
  41. server = socket.socket()
  42. server.bind((host, port))
  43. server.listen()
  44.  
  45. print('Server is Listening.....')
  46.  
  47. while True:  # Keep accepting connections
  48.     conn, addr = server.accept()
  49.     print(f'Accepted connection from {addr}')
  50.    
  51.     # Create a new thread to handle the client
  52.     client_handler = threading.Thread(target=handle_client, args=(conn,))
  53.     client_handler.start()
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement