|
|
- #!/usr/bin/env python3.7
- from Server import Server
-
-
- class ClientConnection(object):
- """
- Client connection object
- """
-
- def __init__(self, server: Server, conn, addr, buffSize=4096, encoding='utf8'):
- self.server = server
- self.conn = conn
- self.addr = addr
- self.name = '{}:{}'.format(addr[0], addr[1])
- self.buffSize = buffSize
- self.encoding = encoding
-
- def serve(self) -> None:
- """
- Server this connection and start lisneting for incoming
- message
- """
- self.send(
- '[system] Type \':quit\' to quit this conversation')
- while True:
- msg = self.recv()
- if msg != ':quit' and len(msg) > 0:
- self.server.sendToAll(self, msg)
- else:
- self.send('[system] :goodbye:')
- break
- self.kill()
-
- def send(self, msg: str, end='\n') -> None:
- """
- Wrapper method for socker.send and encode the message to
- set encoding
- """
- self.conn.send(bytes(msg + end, self.encoding))
-
- def recv(self) -> str:
- """
- Wrapper method for socket.recv and decode the message from
- set encoding
- """
- return self.conn.recv(self.buffSize).decode(self.encoding).split('\n')[0]
-
- def kill(self) -> None:
- """
- Close this connection and remove it from server
- """
- self.conn.close()
- self.server.removeClient(self)
|