def setUp(self): global g_count self.count = g_count g_count += 1 self.req_q = SQS("{}-{}".format(test_req_q, self.count)) self.in_b = S3("{}-{}".format(test_in_b, self.count)) self.out_b = S3("{}-{}".format(test_out_b, self.count)) self.cli = Client("{}-{}".format(test_res_q, self.count), "{}-{}".format(test_req_q, self.count), "{}-{}".format(test_in_b, self.count))
async def action_answer_question( cls, msg, client: Client ) -> Optional[AbstractState]: if "answer_index" not in msg or not isinstance(msg["answer_index"], int): return None if client.current_game is None: logging.error( "Tried to enter %s state without being in a game???", cls.__name__ ) return current_question = client.current_game.round_three_module.current_question if msg["answer_index"] == current_question.correct_index: client.current_game.round_three_module.add_chaser_correct_answer() client.current_answer_index = msg["answer_index"] other_state_transitions = [ c.change_state(RoundThreeStateChaserDidNotAnswer()) for c in client.current_game.round_three_module.chased_clients if c is not client ] if other_state_transitions: asyncio.wait(other_state_transitions) # Think this fixes some of the races idk if not client.current_game.round_three_module.timer_expired: return RoundThreeStateChaserAnswered()
def join(self, client: Client) -> bool: if not self.in_lobby: return False self.guests.append(client) client.current_game = self return True
def main(): """ Command Line Interface entry point :return: None """ Client()
async def action_set_name(cls, msg, client: Client) -> Optional[AbstractState]: try: name: str = cls.extract_received_name(msg) client.display_name = name return HomeState() except InvalidLobbyJoinRequest as inv_name: logging.error(inv_name) return None
async def action_create_lobby(cls, _msg, client: Client) -> Optional[AbstractState]: code = client.game_handler.room_code_handler.create_new_game_code() game = Game(code, client) logging.info(f"Created new lobby, code: {game.code}") client.game_handler.add_game(game) client.current_game = game return HostingLobbyState()
def __init__(self): self._logger = logging.getLogger('ClientMessage') self._input_queue = Queue.Queue() self._output_queue = Queue.Queue() self.i = 0 self._client = Client(self._input_queue, self._output_queue) self._client_model = ClientModel()
def startLogin(self): username = self.getUsername() host = self.getHost() port = self.getPort() try: self.client = Client(username, host, port) self.windowChat = WindowChat(username) # Username is empty or somethings isConnectionFail = self.client.connectToServer() if isConnectionFail: self.dialogChangeUsername() # else: # self.windowChat.setupFriendsList(self.client.peerList) # Track changeing Friend List self.client.change_friend_list.connect(self.windowChat.setupFriendsList) self.client.start() self.windowChat.show() self.close() except: self.showMessageBox("Error", "Can't connect to server %s:%d" % (host, port))
async def action_answer_question( cls, msg, client: Client) -> Optional[AbstractState]: if "answer_index" not in msg or not isinstance(msg["answer_index"], int): return None if client.current_game is None: logging.error("Tried to enter %s state without being in a game???", cls.__name__) return current_question = client.current_game.round_one_module.client_question[ client] if msg["answer_index"] == current_question.correct_index: client.current_game.round_one_module.add_correct_answer(client) client.current_answer_index = msg["answer_index"] return RoundOneStateAnswered()
def main() -> None: def onMessage(msg: Message) -> None: global recvSomething print(f'[{msg.author}]: {msg.content}') recvSomething += 1 global recvSomething with Client() as client: client.setCloseListener(lambda: print(' - closed')) client.setMessageListener(onMessage) print(' - connecting...') client.setAddress('127.0.0.1', 20307) client.setUsername('PythonTest') print(' - waiting for response...') while recvSomething != 2: pass
async def action_answer_question( cls, msg, client: Client) -> Optional[AbstractState]: if "answer_index" not in msg: return None if client.current_game is None: logging.error("Tried to enter %s state without being in a game???", cls.__name__) return round_two_module = client.current_game.round_two_module current_question = round_two_module.client_question[client] if msg["answer_index"] == current_question.correct_index or True: round_two_module.add_correct_answer(client) else: round_two_module.add_incorrect_answer(client) client.current_answer_index = msg["answer_index"] return RoundTwoStateAnswered()
def main(): args = parse() print(args) print(args.list) input_file = args.input_file cli_q_name = args.cli_q srv_q_name = args.srv_q srv_b_name = args.srv_b is_file = args.file words = args.list output_file = args.output_file try: with Client(cli_q_name=cli_q_name, srv_q_name=srv_q_name, srv_b_name=srv_b_name) as cli: cli.run(is_file=is_file, words=words, input_file=input_file, output_file=output_file) except BaseException as e: print("The following error occured:\n{}".format(e))
def send_file(filename, server_ip): packager = File_Packager(filename) client = Client(server_ip) meta_packet, chunks = packager.file_to_chunks() client.send_all_file_chunks(meta_packet, chunks) client.close_socket()
def __init__(self): Client.__init__(self) ai_stats.__init__(self) pass
if len(sys.argv) == 4: player_type = sys.argv[1] player_id = sys.argv[2] rand_idx = int(sys.argv[3]) server_id = CLIENTSIDE_SERVER_LIST[rand_idx] # find out our server info server = get_server_info(server_id, servers_list) print "Starting client for %s with id %s, connecting to server %d" % ( player_type, player_id, server_id) # start our client c = Client(publisher_url=server["server2client"], command_url=server["client2server"], player_type=player_type, player_id=player_id, zmq_context=zmq_root_context, verbose=VERBOSE) # wait a bit and let the gamestate comes in # c.wait_for_initial_gamestate() while c.is_game_running() and c.is_char_alive(): if c.is_server_timeout(): # existing server does not send updates print "player %s: server %d does not send any update, finding another server.." % ( player_id, server_id) # find a new server new_rand_idx = rand_idx while new_rand_idx == rand_idx: new_rand_idx = randint(0, len(CLIENTSIDE_SERVER_LIST) - 1)
def register_new_socket(self, socket): self.sockets_to_clients[socket] = Client(socket, self.game_handler)
from client.Client import Client import time client = Client('/socket.io', "localhost", 9999) client.connect() time.sleep(5) if client.send("{ \"value\": 123}"): print "Message sent" if client.send("\"echome\""): print "Echo message sent" client.disconnect()
from client.Client import Client import string import random def _generate_word(length): # https://gist.github.com/noxan/5845351 VOWELS = "aeiou" CONSONANTS = "".join(set(string.ascii_lowercase) - set(VOWELS)) word = "" for i in range(length): if i % 2 == 0: word += random.choice(CONSONANTS) else: word += random.choice(VOWELS) return word c = Client(serverName="localhost", serverPort=12345, username=_generate_word(12)) c.clientSocket.close()
class TestClientCase(unittest.TestCase): #standard setUp function to create instances of resources # that test cases will use def setUp(self): global g_count self.count = g_count g_count += 1 self.req_q = SQS("{}-{}".format(test_req_q, self.count)) self.in_b = S3("{}-{}".format(test_in_b, self.count)) self.out_b = S3("{}-{}".format(test_out_b, self.count)) self.cli = Client("{}-{}".format(test_res_q, self.count), "{}-{}".format(test_req_q, self.count), "{}-{}".format(test_in_b, self.count)) #standard tearDown function to clean up the resources created in setUp def tearDown(self): exc_type = None exc_val = None exc_tb = None self.cli.__exit__(exc_type, exc_val, exc_tb) self.req_q.__exit__(exc_type, exc_val, exc_tb) self.in_b.__exit__(exc_type, exc_val, exc_tb) self.out_b.__exit__(exc_type, exc_val, exc_tb) #helper function for receiving a message from the request queue def recv_req(self): count = 0 while count < 20: msg = self.req_q.recv() if msg is None: count += 1 continue return Requests.decode(msg["Body"]) else: self.fail("Did not receive request") #Test case which tests whether or not a file request was completed successfully #tests the @Client @request method def test_file_req(self): self.cli.request(is_file=True, words=None, input_file=test_in_file) req = self.recv_req() for key in ["url", "words", "queue_name"]: if key not in req: self.fail("Invalid request") self.in_b.download(req["url"], req["url"]) #Test case which tests whether or not a direct request was completed successfully #tests the @Client @request method def test_direct_req(self): self.cli.request(is_file=False, words=None, input_file=test_in_file) req = self.recv_req() for key in ["text", "words", "queue_name"]: if key not in req: self.fail("Invalid request") #Tests a successful response reception #tests the Client <wait_response> method def test_response(self): #self.out_b.upload("lorem.txt", "a.txt") res = Responses.encode_success("{} a.txt".format(self.out_b.name)) res_q = SQS(self.cli.cli_q_name) res_q.send(res, {}) res = self.cli.wait_response() #Tests a successful error response reception #tests the @Client @wait_response method def test_response_error(self): res = Responses.encode_fail("Test error") res_q = SQS(self.cli.cli_q_name) res_q.send(res, {}) with self.assertRaises(Exception): self.cli.wait_response() #Tests an unsuccessful response reception #tests the @Client @wait_response method def test_no_response(self): with self.assertRaises(Exception): self.cli.wait_response() #Tests a successful reception of the output file #test the @Client @get_file method def test_get_file(self): self.out_b.upload("{}".format(test_in_file), "a.txt") self.cli.get_file("{} {}".format(self.out_b.name, "a.txt")) #Tests an unsuccessful reception of the output file #tests the @Client @get_file method def test_get_no_file(self): with self.assertRaises(Exception): self.cli.get_file("{} {}".format(self.out_b.name, "a.txt")) def xtest_run(self): #TODO: implement? other methods all tested, redundant #"Mock" server run #New Process client.run pass
class ClientMessage: def __init__(self): self._logger = logging.getLogger('ClientMessage') self._input_queue = Queue.Queue() self._output_queue = Queue.Queue() self.i = 0 self._client = Client(self._input_queue, self._output_queue) self._client_model = ClientModel() # Connects to the server def connect_to_server(self, host, port): #TODO: May need to move connect_to_server into worker thread to prevent server messages coming back before we're ready for them connected = self._client.connect_to_server(host, port) if connected == True: self.start_client() return True else: return False # Starts the client communication thread def start_client(self): self._logger.debug('Starting client communication thread.') client_thread = threading.Thread(target=self._client.run) client_thread.start() # Send a message to the server def send_message(self, message): self._input_queue.put(message) # Handle the messages sent by the server def handle_message(self): while self._output_queue.qsize() > 0: message = self._output_queue.get() message_enum = message.get_message_enum() num_args = message.get_num_args() message_args = message.get_args() # Handle move messages if message_enum == MessageEnum.MOVE: valid_move = message_args[0] if valid_move == True: player_enum = message_args[1] old_room = message_args[2] new_room = message_args[3] old_room_str = RoomEnum.to_string(old_room) player_enum_str = PlayerEnum.to_string(player_enum) new_room_str = RoomEnum.to_string(new_room) self._logger.debug('%s moved from "%s" to "%s".', player_enum_str, old_room_str, new_room_str) else: self._logger.debug('Invalid move!') # Handle suggest messages elif message_enum == MessageEnum.SUGGEST: self._logger.debug('Received a suggest message.') # Handle accuse message elif message_enum == MessageEnum.ACCUSE: self._logger.debug('Received an accusation message.') # Handle lobby ready and unready messages elif message_enum == MessageEnum.LOBBY_ADD or message_enum == MessageEnum.LOBBY_READY or message_enum == MessageEnum.LOBBY_UNREADY: # Refresh the lobby with the updated list of player names and ready states # This keeps the lobby in sync in case someone leaves and provides the entire lobby list to new players lobby_list = message_args self._logger.debug('Printing lobby list:') for lobby_entry in lobby_list: player_name = lobby_entry[0] ready_state = lobby_entry[1] self._logger.debug('\t(%s, %s).', player_name, ready_state) # Handle lobby change player message elif message_enum == MessageEnum.LOBBY_CHANGE_PLAYER: player_enum = message_args[0] self._logger.debug('You have been assigned the character "%s".', PlayerEnum.to_string(player_enum)) self._client_model.set_player_enum(player_enum) # Handle game state change message elif message_enum == MessageEnum.GAME_STATE_CHANGE: self._logger.debug('Received a game state change message.') # Handle turn over message elif message_enum == MessageEnum.TURN_OVER: self._logger.debug('Received a turn over message.') # Handle turn begin message elif message_enum == MessageEnum.TURN_BEGIN: player_enum = message_args[0] self._logger.debug('It is now "%s\'s" turn!.', PlayerEnum.to_string(player_enum)) if player_enum == self._client_model.get_player_enum(): self._logger.debug('It is now your turn!') # Handle error message elif message_enum == MessageEnum.ERROR: self._logger.debug('Received an error message.')
class WindowLogin(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.client = None self.windowChat = None self.ui = Ui_MainWindow() self.initUI() def initUI(self): self.setFixedSize(310, 166) self.ui.setupUi(self) self.ui.edtHost.setText(self.getIp()) self.ui.btnLogin.clicked.connect(self.startLogin) def startLogin(self): username = self.getUsername() host = self.getHost() port = self.getPort() try: self.client = Client(username, host, port) self.windowChat = WindowChat(username) # Username is empty or somethings isConnectionFail = self.client.connectToServer() if isConnectionFail: self.dialogChangeUsername() # else: # self.windowChat.setupFriendsList(self.client.peerList) # Track changeing Friend List self.client.change_friend_list.connect(self.windowChat.setupFriendsList) self.client.start() self.windowChat.show() self.close() except: self.showMessageBox("Error", "Can't connect to server %s:%d" % (host, port)) # self.close() def getUsername(self): username = self.ui.edtUsername.text() if username: return username else: self.showMessageBox("Error", "Please enter your username ...\n Try to again") def getHost(self): host = self.ui.edtHost.text() if host: return host else: self.showMessageBox("Error", "Please enter server's host ...\n Try to again") def getPort(self): port = self.ui.edtPort.text() if port: return int(port) else: self.showMessageBox("Error", "Please enter server's port ...\n Try to again") def dialogChangeUsername(self): new_name, okPressed = QInputDialog.getText(self, "Username in user", "Your username", QLineEdit.Normal, "") if okPressed and new_name not in self.client.usernameList: self.windowChat.username = new_name self.windowChat.ui.txtUsername.setText(new_name) self.windowChat.setupFriendsList(self.client.peerList) port = self.client.generateRandomPort() self.client.send_peer_info_to_server(new_name, port) else: self.showMessageBox("Invalid", "Username in use") self.dialogChangeUsername() return new_name def showMessageBox(self, title, msg): return QMessageBox.about(self, title, msg) def getIp(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn't even have to be reachable s.connect(('10.255.255.255', 1)) IP = s.getsockname()[0] except: IP = '127.0.0.1' finally: s.close() return IP