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.

74 lines
2.4 KiB

  1. #!/usr/bin/env python3.7
  2. 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 = '{}:{}'.format(addr[0], addr[1])
  11. self.name = '<anonymous>'
  12. self.buffSize = buffSize
  13. self.encoding = encoding
  14. def nameFormat(self):
  15. return '[{}({})]'.format(self.name, self.addr)
  16. def serve(self) -> None:
  17. """
  18. Serve this connection and start listening for incoming
  19. message
  20. """
  21. self.send(
  22. '[system] You are logged in as [{}({})]\n'.format(self.name, self.addr) +
  23. '[system] Type \'/quit\' to quit this conversation\n' +
  24. '[system] Type \'/name <new name>\' to change your name')
  25. while True:
  26. msg = self.recv()
  27. if len(msg) > 0:
  28. if msg[0] == '/':
  29. cmd = msg[1:5]
  30. if cmd == 'quit':
  31. self.send('[system] :goodbye:')
  32. break
  33. elif cmd == 'name':
  34. tmp = msg.split()
  35. if len(tmp) == 2:
  36. self.server.sendToAll(
  37. self,
  38. "changed name to {}".format(tmp[1]))
  39. self.name = tmp[1]
  40. else:
  41. self.send('[system] whitespace are not allowed')
  42. else:
  43. self.send('[system] unrecognised command')
  44. else:
  45. self.server.sendToAll(self, msg)
  46. else:
  47. break
  48. self.kill()
  49. def send(self, msg: str, end='') -> None:
  50. """
  51. Wrapper method for socker.send and encode the message to
  52. set encoding
  53. """
  54. self.conn.send(bytes(msg + end, self.encoding))
  55. def recv(self) -> str:
  56. """
  57. Wrapper method for socket.recv and decode the message from
  58. set encoding
  59. """
  60. return self.conn.recv(self.buffSize).decode(self.encoding).split('\n')[0]
  61. def kill(self) -> None:
  62. """
  63. Close this connection and remove it from server
  64. """
  65. self.conn.close()
  66. self.server.removeClient(self)