def game_socket(ws: WebSocket) -> None: while not ws.closed: query = ws.receive() if query is None: continue print(f"Received:`{query}`") messages: List[Message] for command in commands: if command.command_matches(query): messages = command.apply_command( matches, query[len(command.STARTS_WITH):]) break else: messages = [Command.error_msg("Invalid command sent", query)] pass for message in messages: if message.add_sender_to_spectate_map: add_client_to_map(message.match_id, ws) msg_to_send_str = to_json_str(message.message) if message.reply_to_only_sender: ws.send(msg_to_send_str) else: removed_clients: List[WebSocket] = [] for client in game_clients[message.match_id]: try: client.send(msg_to_send_str) except WebSocketError: removed_clients.append(client) for client in removed_clients: game_clients[message.match_id].remove(client)
def cmd(ws: WebSocket): ws_id = self.wsCollector.add(ws) while not ws.closed: message = ws.receive() if message is not None: # noinspection PyBroadException msg = {'token': '', 'cmd': None} # noinspection PyBroadException try: msg = json.loads(message) except: msg['cmd'] = message if (msg.get('type', None) is not None) and (msg.get( 'msg', None) is not None): BdsLogger.put_log(msg['type'], msg['msg']) if self.tokenManager.checkToken(msg.get( 'token', '')) or self.wsCollector.check(ws_id): result = self.wsCollector.update(ws_id) if result == 1: ws.send( json.dumps(self.tokenManager.pass_msg, ensure_ascii=False)) self.cmd_in_via_ws(msg.get('cmd', None)) else: ws.send( json.dumps(self.tokenManager.error_msg, ensure_ascii=False))
def send(self, ws: websocket.WebSocket, data: str) -> None: """Send given data to the registered client. Automatically discards invalid connections.""" try: ws.send(data) except Exception: logger.info(f'Player {ws} disconnected from lobby') self.unregister(ws)
def ws(websocket: WebSocket): while not websocket.closed: split_message = websocket.receive().split() action = split_message[0].upper() if action == 'RUN': session_id = split_message[1] if session_id in _valid_session_ids: data = _generator.get_bytes(_BYTES_PER_TRIAL) hit = to_bool(data, _generator.bit_numbering) websocket.send('HIT %d' % (1 if hit else 0)) _log_file.write(f'{utc_datetime_string()},{request.remote_addr},{session_id},{hit},{base64.b64encode(data).decode("utf-8")},{_generator.id},{_generator.bit_numbering.value}\n') _log_file.flush()
def run_trials(websocket: WebSocket, run_id: str, trial_count: int, remote_addr: str): for i in range(trial_count): time.sleep(0.5) data = _generator.get_bytes(_BYTES_PER_TRIAL) gaussian = to_gaussian(data) websocket.send('GAUSSIAN %f' % gaussian) _log_file.write( f'{utc_datetime_string()},{remote_addr},{run_id},{i + 1},{gaussian:.3f},{_generator.id}\n' ) _log_file.flush() _valid_run_ids.remove(run_id)
def ws(websocket: WebSocket): while not websocket.closed: split_message = websocket.receive().split() action = split_message[0].upper() if action == 'PING': _generator.get_bytes(_BYTES_PER_TRIAL) websocket.send('PONG') elif action == 'RUN': run_id = split_message[1] trial_count = int(split_message[2]) if run_id in _valid_run_ids: threading.Thread(target=run_trials, args=(websocket, run_id, trial_count, request.remote_addr)).start()
def game_socket(ws: WebSocket) -> None: while not ws.closed: message = ws.receive() if message is None: continue print(f"Received:`{message}`") msg_to_send: Union[StateDict, CommandResponse] broadcast_id: Optional[str] = None broadcast_only_to_sender = False match_id: str if message == "create": msg_to_send = game_create() elif message == "cards": msg_to_send = list_cards() elif message.startswith("join "): msg_to_send = game_join(message[5:]) if msg_to_send["messageType"] != "error": match_id = msg_to_send["matchId"] broadcast_id = match_id elif message.startswith("state "): msg_to_send = game_state(message[6:]) elif message.startswith("move "): split = message.split(" ") # Command format: move [match_id] [token] [card] [move] # Example: move 5f9c394ee71e1740c218587b iq2V39W9WNm0EZpDqEcqzoLRhSkdD3lY boar a1a2 msg_to_send = game_move(split[1], split[2], split[3], split[4]) if msg_to_send["messageType"] != "error": match_id = msg_to_send["matchId"] broadcast_id = match_id elif message.startswith("spectate "): msg_to_send = game_spectate(message[9:]) if msg_to_send["messageType"] != "error": match_id = msg_to_send["matchId"] add_client_to_map(match_id, ws) broadcast_id = match_id broadcast_only_to_sender = True else: msg_to_send = error_msg("Invalid command sent", message) msg_to_send_str = to_json_str(msg_to_send) ws.send(msg_to_send_str) if broadcast_id is not None: if broadcast_only_to_sender: game_state_str = to_json_str(game_state(broadcast_id)) ws.send(game_state_str) else: broadcast_state(broadcast_id, ObjectId(broadcast_id))
def echo(ws: WebSocket): print("Connection accepted") count = 0 sid = None caller_number = None dad = DetectAndDeter(TEST_NAME) in_queue, out_queue = dad.queues dad.start() dad.make_greeting(ONE_PARTY_RECORDING_CONSENT) while not ws.closed: message = ws.receive() if message is None: continue data = json.loads(message) if data['event'] == "connected": pass elif data['event'] == "start": sid = data['streamSid'] logging.info(data) caller_number = data["start"]["customParameters"]["callerNumber"] # start_recording(data['start']['callSid']) elif data['event'] == "media": in_queue.put(base64.b64decode(data['media']['payload'])) if not out_queue.empty(): ws.send(json.dumps({ "event": "media", "streamSid": sid, "media": { "payload": out_queue.get() }})) elif data['event'] == 'stop': pass elif data['event'] == "closed": break else: raise RuntimeError(f"Unknown event: {data['event']} | data: {data}") count += 1 dad.close() log = dad.fill_log_info(caller_number) logging.info(f"Connection closed | SID: {sid} | messages: {count}") print(f"Connection closed | SID: {sid} | messages: {count}") with open(LOG_PATH/f"call{clean_name(log['start'])}.json", 'w') as f: json.dump(log, f)
def message_socket(ws: WebSocket, connection: Connection) -> None: if Api.__COOKIE_SESSION_NAME not in session: ws.close() return db_session = connection.session() for post in db_session.query(Post).all(): ws.send( Message(datetime=floor(post.datetime.timestamp()), author=post.author, text=post.message).serialize()) with MessageSubscribersQueue.subscribe(request, ws): ws.receive()
def page_socket(socket: WebSocket, page_id): try: page = pages[page_id] except KeyError: socket.close(message="page {} does not exist".format(page_id)) return socket.send(json.dumps({"type": "num_peers", "num_peers": len(page.sockets)})) page.add(socket) print("num sockets", len(page.sockets)) while not socket.closed: message = socket.receive() if message is None: continue page.send(socket, message) page.remove(socket)
def _ws_send_impl( websocket: WebSocket, to_send_msg: str, success_callback: Optional[Callable] = None, success_callback_args: Optional[Dict[str, Any]] = None, failure_callback: Optional[Callable] = None, failure_callback_args: Optional[Dict[str, Any]] = None, ) -> None: try: websocket.send(to_send_msg) except WebSocketError as e: log.error(f'Websocket send with message {to_send_msg} failed due to {str(e)}') if failure_callback: failure_callback_args = {} if failure_callback_args is None else failure_callback_args # noqa: E501 failure_callback(**failure_callback_args) return if success_callback: # send success success_callback_args = {} if success_callback_args is None else success_callback_args # noqa: E501 success_callback(**success_callback_args)
def recognize(self, web_socket: WebSocket): values = list() for i in range(AUDIO_RANGE): src = web_socket.receive() if src is None: logger.info("src is None. {}".format(i)) break audio_data = np.frombuffer(src, dtype="float32") values.append(audio_data) # logger.debug("index:{}, data:{}".format(i, audio_data)) v = np.array(values) v.flatten() # バイナリに16ビットの整数に変換して保存 # -32768 <= int16 <= 32767 arr = (v * 32767).astype(np.int16) file_name = self._create_file_name() with wave.open(file_name, 'wb') as wf: wf.setnchannels(AUDIO_CHANNEL_SIZE) wf.setsampwidth(SAMPLE_WIDTH) wf.setframerate(SAMPLE_RATE) wf.writeframes(arr.tobytes('C')) file_names = [file_name] messages = list() def _report(result: MatchResult): messages.append(result.match_file_names) self._matcher.execute(file_names, _report) self._delete_file(file_name) # flatten messages = list(chain.from_iterable(messages)) # messages = [audfprint/sound/cicada_abra.mp3] object_name = self._get_object_name(messages) if object_name is None: send_message = "Not found" else: send_message = object_name logger.info(send_message) web_socket.send(send_message) self._delete_file(file_name)
def ws_connect(ws: WebSocket): with db_session() as s: np = get_np_json(s) ws.send(json.dumps(dict(type='playing', data=np))) ws.send(json.dumps(dict(type='listeners', data=_listeners(s)))) ws.send( json.dumps( dict(type='queue', data=dict(action="initial", queue=_get_queue())))) ws.send( json.dumps( dict(type='queue', data=dict(action="random", song=get_nr_json())))) pubsub.events.register_client(ws)
def subscribe(ws: WebSocket): """ Connect to the broadcast server and subscribe to telemetry data, which is sent down the WebSocket whenever it is received. """ sock = socket.socket(socket.AF_UNIX) server_address = app.config['BROADCAST_PATH'] try: sock.connect(server_address) except socket.error as e: logging.error('Could not connect to broadcast server.', exc_info=e) ws.close() return sock_file = sock.makefile(mode='r') while True: data = sock_file.readline() if not ws.closed: logging.debug(data.strip()) for datum in separate(json.loads(data)): ws.send(json.dumps(datum))
def ws_connect(ws: WebSocket): with db_session() as s: np = get_np_json(s) ws.send( json.dumps(dict(type='playing', data=pubsub.clear_secret_data(np)))) ws.send( json.dumps( dict(type='listeners', data=pubsub.clear_secret_data(_listeners(s))))) queue = _get_queue() for index, song in enumerate(queue): queue[index] = pubsub.clear_secret_data(song) ws.send( json.dumps( dict(type='queue', data=dict(action="initial", queue=queue)))) ws.send( json.dumps( dict(type='queue', data=dict(action="random", song=pubsub.clear_secret_data(get_nr_json()))))) pubsub.basic.register_client(ws)
def update(ws: WebSocket): if ws and ws in clients and not ws.closed: ws.send(state_json())
def play_chess(ws: WebSocket): while not ws.closed: try: # receive message. message: str = ws.receive() if message is None: continue # message format: `action data` message: list = message.split(' ') # 连接大厅 if message[0] == 'connect': # 已经在大厅里 if ws in hall.users: ws.send(json.dumps({'alert': 'already online'})) continue # 进入大厅 hall.users.update({ws: User(ws, message[1])}) hall.broadcast_rooms() # 进入房间 elif message[0] == 'enter': user = hall.users[ws] room = hall.rooms[message[1]] if user.room is not None: hall.rooms[user.room].users.remove(user) user.status = 'in room' user.room = room.uuid # 房间满了 if len(room.users) == 2: ws.send(json.dumps({'alert': 'full'})) continue # 房间里有一个人 elif len(room.users) == 1: room.users.append(user) room.broadcast() hall.broadcast_rooms() # 房间里没人 else: room.users.append(user) room.broadcast() hall.broadcast_rooms() # 准备 elif message[0] == 'ready': user = hall.users[ws] room = hall.rooms[user.room] user.status = 'ready' # 房间还有其他人 if len(room.users) == 2: another_index = 1 - room.users.index(user) room.users[another_index].ws.send( json.dumps({ 'info': room.users[another_index].name + ' ready' })) room.broadcast() # 对方也准备了,开始游戏 if room.users[another_index].status == 'ready': room.status = 'gaming' room.first_player = random.randint(0, 1) room.cur_player = room.first_player hall.broadcast_rooms() room.users[room.first_player].ws.send( json.dumps({'alert': '你先手'})) room.users[1 - room.first_player].ws.send( json.dumps({'alert': '你后手'})) # 下棋 elif message[0] == 'put': user = hall.users[ws] room = hall.rooms[user.room] if user == room.users[room.cur_player]: room.count += 1 color = room.cur_chess_color() room.board[int(message[2])][int(message[1])] = color room.cur_player = 1 - room.cur_player for user in room.users: user.ws.send(json.dumps({'board': room.board.tolist()})) if room.win(int(message[1]), int(message[2])): room.game_init() winner = user.name for user in room.users: user.ws.send( json.dumps({'result': winner + ' win'})) user.ws.send(json.dumps({'room': room.serialize()})) room.users[0].status = 'in room' room.users[1].status = 'in room' hall.broadcast_rooms() continue elif room.count == 100: room.game_init() for user in room.users: user.ws.send(json.dumps({'result': 'draw'})) user.ws.send(json.dumps({'room': room.serialize()})) room.users[0].status = 'in room' room.users[1].status = 'in room' room.status = 'idle' hall.broadcast_rooms() continue elif message[0] == 'leave': user = hall.users[ws] room = hall.rooms[user.room] room.users.remove(user) user.status = 'online' user.room = None room.game_init() hall.broadcast_rooms() room.broadcast() except Exception as e: print(str(e)) user = hall.users[ws] if user.room is not None: room = hall.rooms[user.room] room.users.remove(user) room.game_init() for user in room.users: user.ws.send(json.dumps({'room': room.serialize()})) del hall.users[ws] hall.broadcast_rooms()
def keep_alive(ws: WebSocket): if ws and ws in clients and not ws.closed: ws.send(state_json()) gevent.spawn_later(50, lambda: keep_alive(ws))