代码之家  ›  专栏  ›  技术社区  ›  P i

如何中断没有任何传入消息的(asyncio)websocket获取循环?

  •  0
  • P i  · 技术社区  · 5 年前

    class OrderStreamer:
        def __init__(ᬑ):
            ᬑ.terminate_flag = False
    
            # worker thread to receive data stream
            ᬑ.worker_thread = threading.Thread(
                target=ᬑ.worker_thread_func,
                daemon=True
                )
    
        def start_streaming(ᬑ, from_scheduler = False):
            ᬑ.worker_thread.start()
    
    
        def terminate(ᬑ):
            ᬑ.terminate_flag = True
    
    
        def worker_thread_func(ᬑ):
            asyncio.run(ᬑ.aio_func())  # blocks
    
    
        async def aio_func(ᬑ):
            async with \
                    aiohttp.ClientSession() as session, \
                    session.ws_connect(streams_url) as wsock, \
                    anyio.create_task_group() as tg:
    
                async for msg in wsock:
                    print(msg.data)
    
                    if ᬑ.terminate_flag:
                        await wsock.close()
    

    terminate_flag 永远不会离开。

    我尝试创建对runloop和websocket的外部引用:

            async with \
                    aiohttp.ClientSession() as session, \
                    session.ws_connect(streams_url) as wsock, \
                    anyio.create_task_group() as tg:
    
                ᬑ.wsock = wsock
                ᬑ.loop = asyncio.get_event_loop()
    

    ... 修改我的终止函数:

        def terminate(ᬑ):
            # ᬑ.loop.stop()
            asyncio.set_event_loop(ᬑ.loop)
    
            async def kill():
                await ᬑ.wsock.close()
    
            asyncio.run(kill())
    

    ... 但它不起作用。

    0 回复  |  直到 5 年前