async def test_new_actions_update_collected_turns(game_api, turn_collector, socketio_server, client, loop): turn_collector.new_turn(1) socketio_client = AsyncClient(reconnection=False) await socketio_client.connect( f"http://{client.server.host}:{client.server.port}?avatar_id=1&EIO=3&transport=polling&t=MJhoMgb" ) wait_action = {"action_type": "wait"} await socketio_client.emit("action", wait_action) await socketio_server.sleep(TIME_TO_PROCESS_SOME_EVENT_LOOP) assert turn_collector.collected_turns.player_id_to_actions[ 1] == wait_action socketio_client_2 = AsyncClient(reconnection=False) await socketio_client_2.connect( f"http://{client.server.host}:{client.server.port}?avatar_id=2&EIO=3&transport=polling&t=MJhoMgb" ) move_action = {"action_type": "move", "options": {"x": 1, "y": 2}} await socketio_client_2.emit("action", move_action) await socketio_server.sleep(TIME_TO_PROCESS_SOME_EVENT_LOOP) assert turn_collector.collected_turns.player_id_to_actions[ 2] == move_action assert len(turn_collector.collected_turns.player_id_to_actions) == 2 await socketio_client.disconnect() await socketio_client_2.disconnect()
def __init__(self, peer): self.client = AsyncClient(reconnection=False, logger=False) self.peer = peer self.app_log = getLogger("tornado.application") self.latest_peer_block = None self.connected = False self.probable_old = False
class DonationAlertsProvider(Provider): """DonationAlerts provider. Handles new donations on donation alerts Config: --- server: str = "https://socket11.donationalerts.ru/socket.io" Default donation alerts server. Secrets: --- donationalerts_token: str = "" Token for donation alerts """ config_vars = Provider.config_vars.copy() config_vars.update({ 'type': 'DonationAlertsProvider', 'name': 'DonationAlertsProvider_name', "server": "https://socket11.donationalerts.ru/socket.io", }) secret_vars = Provider.secret_vars.copy() secret_vars.update({ "donationalerts_token": "" }) def __init__(self, donation_callback): super().__init__(donation_callback) self.sio_da = AsyncClient() self.sio_da.on("connect", handler=self.on_connect) self.sio_da.on("donation", handler=self.on_message) async def on_connect(self, *args): print(f"Connect event to donations alerts server {args}") async def on_message(self, data_str): # update_config() data = json.loads(data_str) print(data, file=sys.stderr) if str(data["alert_type"]) == "1": donation = Donation(data) await self.callback(donation) else: print(f"Unknown message comes from donation alerts{UnknownMessage(data)}") async def connect(self): await self.sio_da.connect(self.config_vars["server"]) await self.sio_da.emit('add-user', {'token': self.secret_vars["donationalerts_token"], 'type': 'alert_widget'}) print(f"Connected to donations alerts server {self.config_vars['server']}") async def disconnect(self): print("Stopping donation alerts") await self.sio_da.disconnect()
class DonationAlertsProvider(Provider): name = "DonationAlertsProvider" config_vars = Provider.config_vars.copy() config_vars.update({ "server": "https://socket11.donationalerts.ru/socket.io", }) secret_vars = Provider.secret_vars.copy() secret_vars.update({ "donationalerts_token": "" }) def __init__(self, action_callback): super().__init__(action_callback) self.sio_da = AsyncClient() self.sio_da.on("connect", handler=self.on_connect) self.sio_da.on("donation", handler=self.on_message) async def on_connect(self, *args): print(f"Connect event to donations alerts server {args}") async def on_message(self, data_str): # update_config() data = json.loads(data_str) print(data, file=sys.stderr) if str(data["alert_type"]) == "1": donation = Donation(data) await self.callback(donation) # if not gtasa.universal_handler(Donation(data).amount): # for k, price in CONFIG["price_handlers"].items(): # if Donation(data).amount == price: # eval(f"{k}()") pass else: print(UnknownMessage(data)) pass async def connect(self): await self.sio_da.connect(self.config_vars["server"]) await self.sio_da.emit('add-user', {'token': self.secret_vars["donationalerts_token"], 'type': 'alert_widget'}) print(f"Connected to donations alerts server {self.config_vars['server']}") # self.sio_da.wait() print(f"Waited?") async def disconnect(self): await self.sio_da.disconnect()
def __init__(self, application_key: str, api_key: str, api_version: int) -> None: """Initialize.""" self._api_key: str = api_key self._api_version: int = api_version self._app_key: str = application_key self._async_user_connect_handler: Optional[Awaitable] = None self._sio: AsyncClient = AsyncClient() self._user_connect_handler: Optional[Callable] = None
def __init__(self, application_key: str, api_key: str, api_version: int) -> None: """Initialize.""" self._api_key: str = api_key self._api_version: int = api_version self._app_key: str = application_key self._async_user_connect_handler: Optional[Callable[..., Awaitable]] = None self._sio: AsyncClient = AsyncClient() self._user_connect_handler: Optional[Callable] = None self._watchdog: WebsocketWatchdog = WebsocketWatchdog(self.reconnect)
def __init__( self, application_key: str, api_key: Union[List[str], str], *, api_version: int = DEFAULT_API_VERSION, logger: logging.Logger = LOGGER, ) -> None: """Initialize.""" if isinstance(api_key, str): api_key = [api_key] self._api_key = api_key self._api_version = api_version self._app_key = application_key self._async_user_connect_handler: Optional[Callable[..., Awaitable]] = None self._logger = logger self._sio = AsyncClient(logger=logger, engineio_logger=logger) self._user_connect_handler: Optional[Callable] = None self._watchdog = WebsocketWatchdog(logger, self.reconnect)
class YadaWebSocketClient(object): WAIT_FOR_PEERS = 20 def __init__(self, peer): self.client = AsyncClient(reconnection=False, logger=False) self.peer = peer self.app_log = getLogger("tornado.application") self.latest_peer_block = None self.connected = False self.probable_old = False async def start(self): try: self.client.manager = self self.client.register_namespace(ClientChatNamespace('/chat')) await self.client.connect("http://{}:{}".format( self.peer['host'], self.peer['port']), namespaces=['/chat']) # self.connected = True await async_sleep(self.WAIT_FOR_PEERS) # wait for an answer if not self.connected: self.app_log.warning( "{} was not connected after {} sec, incrementing fails". format(self.peer.to_string(), self.WAIT_FOR_PEERS)) # await self.peers.increment_failed(self.peer) self.probable_old = True return while self.connected: self.app_log.debug("{} loop, state:{}".format( self.peer.to_string(), self.client.eio.state)) await async_sleep(30) # TODO: poll here after some time without activity? except Exception as e: self.app_log.warning("Exception {} connecting to {}".format( e, self.peer.to_string())) finally: pass
def __init__(self) -> None: """Initialize.""" self._async_disconnect_handler: Optional[Callable[..., Awaitable]] = None self._sio: AsyncClient = AsyncClient() self._sync_disconnect_handler: Optional[Callable[..., Awaitable]] = None self._watchdog: WebsocketWatchdog = WebsocketWatchdog( self.async_reconnect) # Set by async_init(): self._access_token: Optional[str] = None self._namespace: Optional[str] = None
def __init__(self, url='http://localhost:80', connectionTimeout=1, pollTimeout=5, persistent=True, loop=None): # Local import from socketio import AsyncClient, exceptions self._sioExceptions = exceptions self._url = url # Initialize handler and set default callbacks #self._sio = AsyncClient() # SIO client handle # Register message handlers #self._default_register() self._sio = AsyncClient() self._default_register() super().__init__(connectionTimeout=connectionTimeout, pollTimeout=pollTimeout, persistent=persistent, loop=loop)
def __init__(self): self._sio = AsyncClient(request_timeout=300) self.chamber = Chamber() self.hand_in_play = Hand() self.ranks = dict() self.num_cards_remaining = [0 for _ in range(4)] self.dot_colors = ["red" for _ in range(4)] self.gives = [0 for _ in range(4)] self.takes = [0 for _ in range(4)] self.giving_options = list() self.names = ["" for _ in range(4)] self.on_turn = False self.unlocked = False self.pass_unlocked = False self.paused = False self.hands_stored = False
def init_sio_client(settings: Settings, deps: Dependencies, app: FastAPI) -> FastAPI: sio = AsyncClient() url = settings.LISTENER_URL @sio.event def connect(): logger.info(f"Connected to {url}...") @sio.event def disconnect(): logger.info("Disconnecting...") @sio.event async def occurrence(event: OccurrenceEvent): dto = ReportThreatDto( name=event["monsterName"], danger_level=event["dangerLevel"].lower(), location=event["location"][0], ) threat = await threat_service.report_threat(deps.threat_monitor, deps.threat_repository, dto) logger.info(f"Reported threat of name {threat.name}") # App event handlers async def start_listener(): if settings.ENV == Env.testing: return await sio.connect(url) async def stop_listener(): await sio.disconnect() app.on_event("startup")(start_listener) app.on_event("shutdown")(stop_listener) return app
async def client_subscribe(self, client: socketio.AsyncClient, topic: str): await client.emit("subscribe", topic) fut = asyncio.Future() client.on("subscribe", fut.set_result) return await fut
class socketIO(source): ''' Source to interact with Javascript SocketIO servers Supports Javascript SocketIO v1 and v2 ''' def __init__(self, url='http://localhost:80', connectionTimeout=1, pollTimeout=5, persistent=True, loop=None): # Local import from socketio import AsyncClient, exceptions self._sioExceptions = exceptions self._url = url # Initialize handler and set default callbacks #self._sio = AsyncClient() # SIO client handle # Register message handlers #self._default_register() self._sio = AsyncClient() self._default_register() super().__init__(connectionTimeout=connectionTimeout, pollTimeout=pollTimeout, persistent=persistent, loop=loop) # Initialize variables within thread #async def initAsyncVariables(): #future = asyncio.run_coroutine_threadsafe(initAsyncVariables(), self._loop) #future.result(1) def _default_register(self): self._sio.on('connect', self._connect) self._sio.on('disconnect', self._disconnect) self._sio.on('connect_error', self._connectError) ''' async def _shutdown(self): # If already shutdown, there is no action to take so return if self._shutdownFlag is True: return self._shutdownFlag = True self._logger.warn("Shutting down source") # Cancel the command loop self._cmdLoopTask.cancel() # Cancel any active polls if hasattr(self, '_activePolls'): for p in self._activePolls: p.cancel() # Close any open streams await self._close() # If using local threadloop shut it down #if self._tloopLocal: # self.tloop.shutdown() ''' # Default Handlers async def _connect(self): self._connected = True async def _connectError(self, *args): self._connected = False async def _disconnect(self): self._connected = False # Connection managers async def _connect(self): ''' Connect to the data source (if needed) ''' if self._shutdownFlag: return False async with self._connectingLock: if not self._connected: try: await self._sio.connect(self._url) self._connected = True except self._sioExceptions.ConnectionError as ex: self._logger.error(traceback.format_exc()) raise ConnectionException( f"Connection refused to {self._url}: {ex}") except TimeoutError as ex: raise ConnectionException( f'Timed out during connection attempt to {self._url}: {ex}' ) except Exception as ex: raise ConnectionException( f"Unexpected error connecting to {self._url}: %s") return self._connected async def _close(self): if self._connected is not False: self._connected = False await self._sio.disconnect() async def _emit(self, event, data=None, namespace=None, callback=None): if await self._connect(): await self._sio.emit(event, data=data, namespace=namespace, callback=callback) # User callable methods def add(self, event, data=None, namespace=None, callback=None, frequency=DEFAULT_FREQUENCY, repeat=None, wait=None): h = lambda: self._emit( event, data=data, namespace=namespace, callback=callback) self.poll(handler=h, frequency=frequency, repeat=repeat, wait=wait) def emit(self, event, data=None, namespace=None, callback=None): self.checkAlive() asyncio.run_coroutine_threadsafe( self._emit(event, data=data, namespace=namespace, callback=callback), self._loop) def subscribe(self, channel, handler=None, namespace=None): self.checkAlive() self._sio.on(channel, handler=handler, namespace=namespace)
def __init__(self, donation_callback): super().__init__(donation_callback) self.sio_da = AsyncClient() self.sio_da.on("connect", handler=self.on_connect) self.sio_da.on("donation", handler=self.on_message)
class YadaWebSocketClient(object): WAIT_FOR_PEERS = 20 def __init__(self, peer): self.client = AsyncClient(reconnection=False, logger=False) self.peer = peer self.config = get_config() self.consensus = self.config.consensus self.peers = self.config.peers self.app_log = getLogger("tornado.application") self.latest_peer_block = None self.connected = False self.probable_old = False async def start(self): try: self.client.manager = self self.client.register_namespace(ClientChatNamespace('/chat')) url = "http://{}:{}".format(self.peer.host, self.peer.port) self.app_log.info("ws client connecting to {}".format(url)) await self.client.connect(url, namespaces=['/chat']) # self.connected = True await async_sleep(self.WAIT_FOR_PEERS) # wait for an answer if not self.connected: self.app_log.warning( "{} was not connected after {} sec, incrementing fails". format(self.peer.to_string(), self.WAIT_FOR_PEERS)) # await self.peers.increment_failed(self.peer) self.probable_old = True return if self.peer.host not in self.config.peers.outbound: # if we are not in the outgoing, we did not receive a peers answer, old peer (but ok) self.app_log.warning( "{} was not connected after {} sec, probable old node". format(self.peer.to_string(), self.WAIT_FOR_PEERS)) self.probable_old = True await self.client.disconnect() return while self.connected: self.app_log.debug("{} loop, state:{}".format( self.peer.to_string(), self.client.eio.state)) # This is a mess, surely we can do better. if self.client.eio.state == 'disconnected': self.connected = False return await async_sleep(30) # TODO: poll here after some time without activity? except Exception as e: self.app_log.warning("Exception {} connecting to {}".format( e, self.peer.to_string())) finally: pass async def on_latest_block(self, data): from yadacoin.block import Block # Circular reference. Not good! - Do we need the object here? # processing in this object rather than ClientChatNamespace so consensus data is available from peers self.latest_peer_block = Block.from_dict(data) if not self.peers.syncing: self.app_log.debug("Trying to sync on latest block from {}".format( self.peer.to_string())) my_index = self.config.BU.get_latest_block()['index'] if data['index'] == my_index + 1: self.app_log.debug( "Next index, trying to merge from {}".format( self.peer.to_string())) if await self.consensus.process_next_block(data, self.peer): pass # if ok, block was inserted and event triggered by import block # await self.peers.on_block_insert(data) elif data['index'] > my_index + 1: self.app_log.debug( "Missing blocks between {} and {} , asking more to {}". format(my_index, data['index'], self.peer.to_string())) data = { "start_index": my_index + 1, "end_index": my_index + 1 + CHAIN.MAX_BLOCKS_PER_MESSAGE } await self.client.emit('get_blocks', data=data, namespace="/chat") elif data['index'] == my_index: self.app_log.debug("Same index, ignoring {} from {}".format( data['index'], self.peer.to_string())) else: # We have better self.app_log.debug( "We have higher index, sending {} to ws {}".format( data['index'], self.peer.to_string())) block = self.config.BU.get_latest_block() block['time_utc'] = ts_to_utc(block['time']) await self.client.emit('latest_block', data=block, namespace="/chat") async def on_blocks(self, data): my_index = self.config.BU.get_latest_block()['index'] if data[0]['index'] != my_index + 1: return self.peers.syncing = True try: inserted = False block = None # Avoid linter warning for block in data: # print("looking for ", self.existing_blockchain.blocks[-1].index + 1) if block['index'] == my_index + 1: if await self.consensus.process_next_block( block, self.peer, trigger_event=False): inserted = True my_index = block['index'] else: break else: # As soon as a block fails, abort break if inserted: # If import was successful, inform out peers once the batch is processed await self.peers.on_block_insert(block) # then ask for the potential next batch data = { "start_index": my_index + 1, "end_index": my_index + 1 + CHAIN.MAX_BLOCKS_PER_MESSAGE } await self.client.emit('get_blocks', data=data, namespace="/chat") else: self.app_log.debug("Import aborted block: {}".format(my_index)) return except Exception as e: import sys, os self.app_log.warning("Exception {} on_blocks".format(e)) exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno) finally: self.peers.syncing = False
try: from socketio import AsyncClient from socketio.exceptions import ConnectionError except (ImportError, ModuleNotFoundError): raise ImportError( "To use telemetry you must install the `telemetry` option. (run `pip install -U dogehouse[telemetry]`)" ) from json import dumps socket = AsyncClient() activated = False err_occurred_on_connect = False @socket.event async def connect(): global activated activated = True async def transmit(client): global activated, err_occurred_on_connect if err_occurred_on_connect: return await start() if not activated or not hasattr(client.user, "id"): return
class Websocket: # pylint: disable=too-many-instance-attributes """Define the websocket.""" def __init__( self, application_key: str, api_key: Union[List[str], str], *, api_version: int = DEFAULT_API_VERSION, logger: logging.Logger = LOGGER, ) -> None: """Initialize.""" if isinstance(api_key, str): api_key = [api_key] self._api_key = api_key self._api_version = api_version self._app_key = application_key self._async_user_connect_handler: Optional[Callable[..., Awaitable]] = None self._logger = logger self._sio = AsyncClient(logger=logger, engineio_logger=logger) self._user_connect_handler: Optional[Callable] = None self._watchdog = WebsocketWatchdog(logger, self.reconnect) async def _init_connection(self) -> None: """Perform automatic initialization upon connecting.""" await self._sio.emit("subscribe", {"apiKeys": self._api_key}) await self._watchdog.trigger() if self._async_user_connect_handler: await self._async_user_connect_handler() elif self._user_connect_handler: self._user_connect_handler() def async_on_connect(self, target: Callable[..., Awaitable]) -> None: """Define a coroutine to be called when connecting.""" self._async_user_connect_handler = target self._user_connect_handler = None def on_connect(self, target: Callable) -> None: """Define a method to be called when connecting.""" self._async_user_connect_handler = None self._user_connect_handler = target def async_on_data(self, target: Callable[..., Awaitable]) -> None: # noqa: D202 """Define a coroutine to be called when data is received.""" async def _async_on_data(data: Dict[str, Any]) -> None: """Act on the data.""" await self._watchdog.trigger() await target(data) self._sio.on("data", _async_on_data) def on_data(self, target: Callable) -> None: # noqa: D202 """Define a method to be called when data is received.""" async def _async_on_data(data: Dict[str, Any]) -> None: """Act on the data.""" await self._watchdog.trigger() target(data) self._sio.on("data", _async_on_data) def async_on_disconnect(self, target: Callable[..., Awaitable]) -> None: """Define a coroutine to be called when disconnecting.""" self._sio.on("disconnect", target) def on_disconnect(self, target: Callable) -> None: """Define a method to be called when disconnecting.""" self._sio.on("disconnect", target) def async_on_subscribed( self, target: Callable[..., Awaitable]) -> None: # noqa: D202 """Define a coroutine to be called when subscribed.""" async def _async_on_subscribed(data: Dict[str, Any]) -> None: """Act on subscribe.""" await self._watchdog.trigger() await target(data) self._sio.on("subscribed", _async_on_subscribed) def on_subscribed(self, target: Callable) -> None: # noqa: D202 """Define a method to be called when subscribed.""" async def _async_on_subscribed(data: Dict[str, Any]) -> None: """Act on subscribe.""" await self._watchdog.trigger() target(data) self._sio.on("subscribed", _async_on_subscribed) async def connect(self) -> None: """Connect to the socket.""" try: self._sio.on("connect", self._init_connection) await self._sio.connect( f"{WEBSOCKET_API_BASE}/?api={self._api_version}&applicationKey={self._app_key}", transports=["websocket"], ) except ( ClientConnectionError, ClientOSError, SIOConnectionError, SocketIOError, ) as err: raise WebsocketError(err) from err async def disconnect(self) -> None: """Disconnect from the socket.""" await self._sio.disconnect() self._watchdog.cancel() async def reconnect(self) -> None: """Reconnect the websocket connection.""" await self.disconnect() await asyncio.sleep(1) await self.connect()
if __name__ == '__main__': # -----------------=-------------------------=-------------------=-------------=- # -----------------=-------------------------=-------------------=-------------=- IpAddress = '192.168.29.98' PORT = '8080' clientName = 'Iron Man' roomName = 'Marvel' # -----------------=-------------------------=-------------------=-------------=- # -----------------=-------------------------=-------------------=-------------=- sio = AsyncClient() FullIp = 'http://' + IpAddress + ':' + PORT @sio.event async def connect(): print('Connected to sever') await sio.emit('join_chat', {'room': roomName, 'name': clientName}) @sio.event async def get_message(message): if clientName == message['from']: print('You : ' + message['message']) else: print(message['from'] + ' : ' + message['message']) async def send_message():