Guest User

Server.py

a guest
Oct 16th, 2017
2,677
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. # Code for:
  2. # https://stackoverflow.com/questions/46775320/simple-python-server-client-file-transfer
  3.  
  4. import socket
  5.  
  6. ssFT = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  7. ssFT.bind((socket.gethostname(), 8756))
  8. ssFT.listen(1)
  9. while True:
  10.     (conn, address) = ssFT.accept()
  11.     text_file = 'fileProj.txt'
  12.  
  13.     #Receive, output and save file
  14.     with open(text_file, "wb") as fw:
  15.         print("Receiving..")
  16.         while True:
  17.             print('receiving')
  18.             data = conn.recv(32)
  19.             if data == b'BEGIN':
  20.                 continue
  21.             elif data == b'ENDED':
  22.                 print('Breaking from file write')
  23.                 break
  24.             else:
  25.                 print('Received: ', data.decode('utf-8'))
  26.                 fw.write(data)
  27.                 print('Wrote to file', data.decode('utf-8'))
  28.         fw.close()
  29.         print("Received..")
  30.  
  31.     #Append and send file
  32.     print('Opening file ', text_file)
  33.     with open(text_file, 'ab+') as fa:
  34.         print('Opened file')
  35.         print("Appending string to file.")
  36.         string = b"Append this to file."
  37.         fa.write(string)
  38.         fa.seek(0, 0)
  39.         print("Sending file.")
  40.         while True:
  41.             data = fa.read(1024)
  42.             conn.send(data)
  43.             if not data:
  44.                 break
  45.         fa.close()
  46.         print("Sent file.")
  47.     break
  48. ssFT.close()
Add Comment
Please, Sign In to add comment