Search code examples
pythonwebsocketpython-asyncio

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()
    await 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
    await do_something_with_latest_message(msg)

Solution

  • 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())