You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 regels
1.5 KiB

  1. #!/usr/bin/env python3.7
  2. from Server import Server
  3. class ClientConnection(object):
  4. """
  5. Client connection object
  6. """
  7. def __init__(self, server: Server, conn, addr, buffSize=4096, encoding='utf8'):
  8. self.server = server
  9. self.conn = conn
  10. self.addr = addr
  11. self.name = '{}:{}'.format(addr[0], addr[1])
  12. self.buffSize = buffSize
  13. self.encoding = encoding
  14. def serve(self) -> None:
  15. """
  16. Server this connection and start lisneting for incoming
  17. message
  18. """
  19. self.send(
  20. '[system] Type \':quit\' to quit this conversation')
  21. while True:
  22. msg = self.recv()
  23. if msg != ':quit' and len(msg) > 0:
  24. self.server.sendToAll(self, msg)
  25. else:
  26. self.send('[system] :goodbye:')
  27. break
  28. self.kill()
  29. def send(self, msg: str, end='\n') -> None:
  30. """
  31. Wrapper method for socker.send and encode the message to
  32. set encoding
  33. """
  34. self.conn.send(bytes(msg + end, self.encoding))
  35. def recv(self) -> str:
  36. """
  37. Wrapper method for socket.recv and decode the message from
  38. set encoding
  39. """
  40. return self.conn.recv(self.buffSize).decode(self.encoding).split('\n')[0]
  41. def kill(self) -> None:
  42. """
  43. Close this connection and remove it from server
  44. """
  45. self.conn.close()
  46. self.server.removeClient(self)