简体   繁体   中英

Get latest message from websockets queue in Python

How do you get the last message received from server even if there are unread messages in queue?

Also, how could I ignore (delete) the rest of the unread messages?

CODE example:

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

I Nead something like:

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)

There's no way to do this natively, just with the websockets library. However, you could use an 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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM