|
|
- #!/usr/bin/env python3.7
- import threading
- from ChatConnection import ChatConnection
-
-
- class ChatInterface(object):
- def __init__(self,
- connection: ChatConnection,
- name: str = '<anonymous>'):
- # set connection to use
- self.connection = connection
- self.name = name
-
- def send(self, msg) -> None:
- """
- Send message to connection
- """
- self.connection.send(msg)
- # check if input is quit command
- if self.connection.isOpen:
- if msg[0] == '/':
- cmd = msg[1:5]
- if cmd == 'quit':
- self.connection.close()
- elif cmd == 'name':
- tmp = msg.split()
- if len(tmp) == 2:
- self.name = tmp[1]
-
- def listener(self) -> None:
- """
- Listener method to keep receiving new message from
- connection
- """
- while self.connection.isOpen:
- # receive messages from connection
- msg = self.connection.recv()
- if len(msg) > 0:
- # add recevied message to message list
- print('\r' +
- msg +
- '\n' +
- '[ME({})]: '.format(self.name), end='')
- else:
- self.connection.close()
-
- def start(self) -> None:
- # initialise background listener as daemon thread
- backgroundListener = threading.Thread(target=self.listener)
- backgroundListener.daemon = True
- backgroundListener.start()
-
- self.send('/name {}'.format(self.name))
-
- while self.connection.isOpen:
- try:
- msg = input('[ME({})]: '.format(self.name))
- except (EOFError, KeyboardInterrupt):
- msg = '/quit'
- finally:
- self.send(msg)
|