从Python中的websockets队列获取最新消息



即使队列中有未读消息,您如何获得从服务器收到的最后一条消息?

此外,我如何忽略(删除(其余未读邮件?

代码示例:

while True:
msg = await ws_server.recv()
await 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
await 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())

最新更新