I use two streams: the first one listens to WebSocket, the second one runs only once, in order to subscribe the application to events after the WebSocket start.
import aiohttp import requests import json import threading ws_connected = False сlass ProcessEvent(object): # Some class def __init__(self): pass class WSListenerThread(threading.Thread): def run(self): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(listen()) async def listen(): async with aiohttp.ClientSession(auth=ARI_AUTH) as session: async with session.ws_connect('ws://localhost/events') as ws: ws_connected = True async for msg in ws: event = ProcessEvent(msg=msg.data) await event.check() class Subscriber(threading.Thread): def run(self): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(self.resubscribe()) def resubscribe(): while not ws_connected: pass requests.post("http://localhost/something", data="payload=") if __name__ == '__main__': try: event_listener = WSListenerThread() event_listener.start() subscriber = Subscriber() subscriber.start() except KeyboardInterrupt: print("Pressing \"<CTRL> + <C>\".") # Как отправить сигнал на закрытие WS в потоке event_listener? sys.exit(0) How to close the stream from the outside?