websockets icon indicating copy to clipboard operation
websockets copied to clipboard

Creating a Data Stream on Server (Push data)

Open NashTools opened this issue 5 years ago • 1 comments

I have an application which periodically computes new data and I want to send that data from a server to all connected clients, in pseudo code it could look like this: while True: res = calc_res(); websocket.send(res); sleep(1000) However, the websocket callback only gets called, when a client either connects to the server or sends a message to the server. I that case the client would have to actively send messages in order to pull data, I would prefer it it the server pushed the data instead. Is this possible? I tried to store the websocket in a global variable, but that didn't work either.

Thank you

NashTools avatar Oct 15 '21 16:10 NashTools

Yes, this is possible.

You need to:

  • store connections in a global variable (this is described in the docs)
  • run an asyncio task alongside the server to broadcast messages

I'm going to reopen and check if this could be better documented.

aaugustin avatar Oct 17 '21 08:10 aaugustin