Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. import socket
  2. import sys
  3. import threading
  4.  
  5. class Server:
  6. def __init__(self, host, port):
  7. self.host = host
  8. self.port = port
  9.  
  10. def run(self):
  11. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  12. s.bind((self.host, self.port))
  13. s.listen()
  14. while True:
  15. conn, addr = s.accept()
  16. t = threading.Thread(None, Server.process_connection, "conn-"+str(addr), (conn, addr))
  17. t.start()
  18.  
  19. @staticmethod
  20. def process_connection(connection, address):
  21. BUFFER_SIZE = 1024
  22. with connection:
  23. print('Connected to', address)
  24. name_len = int.from_bytes(Server._read(connection, 4), 'little')
  25. name = str(Server._read(connection, name_len), 'utf-8')
  26. print('Receiving ' + name)
  27. while True:
  28. data = connection.recv(BUFFER_SIZE)
  29. if not data:
  30. break
  31. with open('storage/' + name, 'ab') as f:
  32. f.write(data)
  33. print("Received " + name)
  34.  
  35. @staticmethod
  36. def _read(conn, num):
  37. data = conn.recv(num)
  38. if not data:
  39. raise Exception("Read operation failed")
  40. return data
  41.  
  42. if __name__ == "__main__":
  43. HOST = sys.argv[1] if len(sys.argv) > 1 else '' # any
  44. PORT = sys.argv[2] if len(sys.argv) > 2 else 65432
  45.  
  46. s = Server(HOST, PORT)
  47. s.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement