简体   繁体   English

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

[英]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?另外,我怎么能忽略(删除)未读邮件的 rest?

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.仅使用websockets库就无法在本地执行此操作。 However, you could use an asyncio.LifoQueue :但是,您可以使用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