簡體   English   中英

從 Python 中的 websockets 隊列獲取最新消息

[英]Get latest message from websockets queue in Python

即使隊列中有未讀消息,如何獲取從服務器收到的最后一條消息?

另外,我怎么能忽略(刪除)未讀郵件的 rest?

代碼示例:

while True:
    msg = await ws_server.recv()
    do_something_with_latest_message(msg)

我需要類似的東西:

while True:
    msg = await ws_server.recv_last_msg() # On next loop I should "await" until a newer msg comes, not te receive the previous msg in LIFO order
    do_something_with_latest_message(msg)

僅使用websockets庫就無法在本地執行此操作。 但是,您可以使用asyncio.LifoQueue

queue = asyncio.LifoQueue()

async def producer(ws_server):
    async for msg in ws_server:
        await queue.put(msg)

async def consumer():
    while True:
        msg = await queue.get()
        # clear queue
        while not queue.empty():
            await queue.get()
        await do_something_with_latest_message(msg)
await asyncio.gather(producer(ws_server), consumer())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM