python-websockets / websockets

Library for building WebSocket servers and clients in Python
https://websockets.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
5.16k stars 513 forks source link

streaming websockets client - SUBSCRIBE #1392

Closed gborrageiro closed 1 year ago

gborrageiro commented 1 year ago

Hello,

Is it possible to create a streaming websockets client that subscribes to a url-based topic, and receives this information as and when it arrives?

I am familiar with the classical REQUEST-type example:

async with websockets.connect(self.ws_socket) as ws:
    while True:
        payload = json.dumps(
            {
                "method": "REQUEST",
                "params": [
                    f"{self.listen_key}@account", f"{self.listen_key}@balance"
                ],
                "id": 123,
            }
        )
        await ws.send(payload)
        try:
            res = json.loads(await asyncio.wait_for(ws.recv(), timeout=60))
            print(res)
        except asyncio.TimeoutError:
            print("No response after 60s: timeout!")

        await asyncio.sleep(0.1)

The problem with the above approach is that I am forced to poll the server once every 100 milliseconds; any faster, and my request returns an error. The data I wish to receive arrives asynchronously. websockets.serve appears to offer something which could be of value: a method to call back on. But I'm not quite running a server locally. In summary, how could I arrange the above code snippet such that I can receive data asynchronously as and when it arrives?

Thanks Gabriel

aaugustin commented 1 year ago

I don't understand your question. ws.recv() gives you the data as and when it arrives.

Also, I don't know what response is expected from the server. Is it going to send one message? That's what your code expects. Or is it going to send several messages?

Can you share the API documentation of the server? That would help.