SHARE
TWEET

Untitled

a guest Oct 21st, 2019 61 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import socket
  2. import os, sys
  3. from time import sleep
  4.  
  5. def transfer_progress(percent_done):
  6.     if percent_done==100:
  7.         output_text = f"\rTransfer Complete!   (100% done)                  "
  8.     else:
  9.         output_text = f"\rTransfer in progress:  {percent_done:.2f} %"
  10.     sys.stdout.write(output_text)
  11.     sys.stdout.flush()
  12.     #sleep(0.15)
  13.  
  14. def main(file_name, host, port):
  15.     # Connect to the server
  16.     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  17.     sock.connect((host, port))
  18.  
  19.     print(f"Begin transfer of '{file_name}' to {host} : {port}")
  20.  
  21.     try:
  22.         f = open(file_name, 'rb')
  23.     except:
  24.         raise Exception('Error reading the specified file!')
  25.  
  26.     size = os.path.getsize(file_name)   # Get size of the file to be sent first.
  27.     sock.send(file_name.encode())       # Send the name of the file to the server.
  28.  
  29.     response = int(sock.recv(1).decode())    # Get integer bit 0 or 1 as acknowledgement/response
  30.     if response:
  31.         total = 0
  32.         percent = total / size
  33.         # Initialise progress bar
  34.         transfer_progress(percent)
  35.         data = f.read(1024)
  36.         # Send data
  37.         while data:
  38.             sock.send(data)
  39.             total += 1024
  40.             percent = total / size
  41.             if percent > 1:
  42.                 percent = 1
  43.             transfer_progress(percent * 100)
  44.             data = f.read(1024)
  45.     else:
  46.         print("Error: Sending {} failed!".format(file_name))
  47.     sock.close()
  48.  
  49.  
  50. if __name__ == "__main__":
  51.     args = sys.argv
  52.  
  53.     if len(args) != 4:
  54.         print('Argument Error: Program expects exactly 3 arguments: -file_name -hostname -portnumber')
  55.     else:
  56.         main(args[1], args[2], int(args[3]))
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top