Using Python websockets to receive latest message

Viewed 212

I'm looking to implement something similar to the on_message functionality WebSocketApp but using the websockets library, i.e. always read the latest message. However it looks like they only offer recv() in order to read the next message in the queue.

My temporary work around is to run ws.recv() in a while loop, but I'm not sure whether this is the right approach:

async with websockets.connect(self.socket) as ws:
    while True:
        msg = await asyncio.wait_for(ws.recv(), timeout=3)
        self.on_msg(msg)

With this approach I have two concerns:

  1. I'm subscribed to a very high-frequency channel, so I'm concerned recv will fall behind in reading the messages in the queue. (I previously had a 0.1s delay in the while loop and noticed that the message I was getting was not the latest. Even after terminating my internet connection, it kept reading from the message queue before raising a connection closed error)

  2. I'm currently using a timeout to detect if a message hangs for unforeseen reasons, but there are cases where there are simply no messages and it raises a timeout error. I'm not able to differentiate the two using the current method.

What's the best way to always get the latest message, even if there's a queue of unread messages? Also, how would you do error handling to avoid the issue in 2)?

0 Answers
Related