def handle_message(self, message): """Delegate the message to the appropriate object Arguments: message -- a message type """ PM = PokerMessage MT = MessageTypes ET = ErrorTypes try: if message[PM.MESSAGE_TYPE] == MT.PLAYER_ACTION: action_type = message[MT.PLAYER_ACTION] responses = self.handle_player_action(action_type) elif message[PM.MESSAGE_TYPE] == MT.PLAYER_UPDATE_REQUEST: request = message[MT.PLAYER_UPDATE_REQUEST] responses = self.handle_update_request(request) except PlayerActionError: text = 'An error occurred when the action was played.' text = text + ' Please try again.' error_type = ET.ACTION_ERROR print(traceback.format_exc()) error = GameError(error_type, text, traceback.format_exc()) error.log() responses = [error.make_message()] except PlayerControlError: text = 'An error occurred due to the player control.' error_type = ET.PLAYER_CONTROL_ERROR error = GameError(error_type, text, traceback.format_exc()) error.log() responses = [error.make_message()] except GameControlError: text = 'An error occurred due to the game control.' error_type = ET.GAME_CONTROL_ERROR error = GameError(error_type, text, traceback.format_exc()) error.log() responses = [error.make_message()] except UpdateRequestError: text = 'An error occurred due to the update request.' error_type = ET.UPDATE_REQUEST_ERROR error = GameError(error_type, text, traceback.format_exc()) error.log() responses = [error.make_message()] except: text = 'An unknown error occurred.' error_type = ET.UNCAUGHT_EXCEPTION error = GameError(error_type, text, traceback.format_exc()) error.log() responses = [error.make_message()] finally: return responses
def listen(self): """Listen for messages from users and pass them on to the controller""" ET = ErrorTypes s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(5) while self.port is None: try: host, port = self.port_manager.get_next_port() s.bind((host, port)) self.port = port except: pass s.listen(20) while not self.done: try: client_socket, address = s.accept() messages = NetMessage.get_message(client_socket) for message in messages: replies = [] try: replies = self.controller.handle_message(message) except: text = "Uncaught exception" error_type = ET.UNCAUGHT_EXCEPTION error_message = GameError(error_type, text, traceback.format_exc()) replies = [error_message.make_message()] NetMessage.send_message(client_socket, replies) client_socket.close() except socket.timeout: pass s.close()