|
|
- #!/usr/bin/env python3.7
- import socket
-
-
- class ChatConnection(object):
- def __init__(self, host: str, port: int, buffSize=4096, encoding='utf8'):
- self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self.soc.connect((host, port))
- self.buffSize = buffSize
- self.encoding = encoding
- self.isOpen = True
-
- def send(self, msg: str) -> None:
- """
- Wrapper method of socket.send and encode the message
- to set character encoding.
- """
- try:
- self.soc.send(bytes(msg, self.encoding))
- except OSError:
- self.close()
-
- def recv(self) -> str:
- """
- Wrapper method of socket.recv and encode the message
- to set character encoding.
- """
- return self.soc.recv(self.buffSize).decode(self.encoding)
-
- def close(self) -> None:
- """
- Wrapper method to close the socket
- """
- self.soc.close()
- self.isOpen = False
|