1

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)

1 Answer 1

1

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())
Sign up to request clarification or add additional context in comments.

4 Comments

I can't test it right now, but it seems like a solution
Second time the code goes through async for msg in ws_server: in producer function it raises this error RuntimeError: Task <Task pending name='Task-11' coro=<consumer() running at xxx\main.py:139> cb=[_gather.<locals>._done_callback() at xxx\asyncio\tasks.py:767]> got Future <Future pending> attached to a different loop. Line 139 referenced in the error is the msg = await queue.get() of the consumer function.
This should solve your issue.
Nevermind, it's working. I call the await asyncio.gather(prod, cons) instruction inside an async with websockets.connect context manager, but the asyncio.LifoQueue() outside of it. I put the queue declaration inside the context manager and passed it as parameter to the producer and consumer and it's working now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.