|
|
- #!/usr/bin/env python3.7
- 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 = '{}:{}'.format(addr[0], addr[1])
- self.name = '<anonymous>'
- self.buffSize = buffSize
- self.encoding = encoding
-
- def nameFormat(self):
- return '[{}({})]'.format(self.name, self.addr)
-
- def serve(self) -> None:
- """
- Serve this connection and start listening for incoming
- message
- """
- self.send(
- '[system] You are logged in as [{}({})]\n'.format(self.name, self.addr) +
- '[system] Type \'/quit\' to quit this conversation\n' +
- '[system] Type \'/name <new name>\' to change your name')
- while True:
- msg = self.recv()
- if len(msg) > 0:
- if msg[0] == '/':
- cmd = msg[1:5]
- if cmd == 'quit':
- self.send('[system] :goodbye:')
- break
- elif cmd == 'name':
- tmp = msg.split()
- if len(tmp) == 2:
- self.server.sendToAll(
- self,
- "changed name to {}".format(tmp[1]))
- self.name = tmp[1]
- else:
- self.send('[system] whitespace are not allowed')
- else:
- self.send('[system] unrecognised command')
- else:
- self.server.sendToAll(self, msg)
- else:
- break
- self.kill()
-
- def send(self, msg: str, end='') -> 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)
|