Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. import socket
  2. from os.path import exists, splitext
  3. from threading import Thread
  4.  
  5. # Thread to listen one particular client
  6. class ClientListener(Thread):
  7. def __init__(self, sock: socket.socket):
  8. super().__init__(daemon=True)
  9. self.sock = sock
  10.  
  11. def run(self):
  12. #getting filename and first piece of file
  13. #they are splitted by special FS (file separator) character
  14. chunk = self.sock.recv(1024)
  15. filename, data = chunk.split(b'\034', 1)
  16. path = filename.decode('utf-8')
  17. name, format = splitext(path)
  18. i = 0
  19. while exists(path):
  20. path = name + '_copy' + str('' if i == 0 else i) + format
  21. i += 1
  22. with open(path, 'wb+') as file:
  23. file.write(data)
  24. while True:
  25. # try to read 1024 bytes from user
  26. # this is blocking call, thread will be paused here
  27. data = self.sock.recv(1024)
  28. if data:
  29. file.write(data)
  30. else:
  31. # if we got no data – client has disconnected
  32. file.close()
  33. print("Connection from", addr, 'is closed')
  34. # finish the thread
  35. return
  36.  
  37.  
  38. # AF_INET – IPv4, SOCK_STREAM – TCP
  39. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  40. # reuse address; in OS address will be reserved after app closed for a while
  41. # so if we close and immediately start server again – we'll get error
  42. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  43. # listen to all interfaces at 1234 port
  44. sock.bind(('', 1234))
  45. sock.listen()
  46. while True:
  47. # blocking call, waiting for new client to connect
  48. con, addr = sock.accept()
  49. print("Connection from", addr)
  50. # start new thread to deal with client
  51. ClientListener(con).start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement