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.

30 lines
867 B

  1. #!/usr/bin/env python3.7
  2. import socket
  3. class ChatConnection(object):
  4. def __init__(self, host: str, port: int, buffSize=4096, encoding='utf8'):
  5. self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  6. self.soc.connect((host, port))
  7. self.buffSize = buffSize
  8. self.encoding = encoding
  9. def send(self, msg: str) -> None:
  10. """
  11. Wrapper method of socket.send and encode the message
  12. to set character encoding.
  13. """
  14. self.soc.send(bytes(msg, self.encoding))
  15. def recv(self) -> str:
  16. """
  17. Wrapper method of socket.recv and encode the message
  18. to set character encoding.
  19. """
  20. return self.soc.recv(self.buffSize).decode(self.encoding)
  21. def close(self) -> None:
  22. """
  23. Wrapper method to close the socket
  24. """
  25. self.soc.close()