Python websockets send to client and keep connection alive
Presumably your function that processes the data is blocking, otherwise you'd simply await
it inside the coroutine. The straightforward approach is to use run_in_executor
to run it in another thread, and await
it in your handler coroutine:
async def hello(websocket, path):
loop = asyncio.get_event_loop()
await websocket.send("Hello Client! Please wait for your data.")
data = await loop.run_in_executor(None, get_data)
await websocket.send("Your data is here!")
await websocket.send(data)
def get_data():
# something that takes a long time to calculate
x = 19134702400093278081449423917**300000 % 256
return bytes([x])
To keep the connection open do not terminate the handler after processing the first message. For example, you can have an endless-loop that will keep processing the incoming messages until the connection is closed by the client:
async def hello(websocket, path):
while True:
try:
name = await websocket.recv()
except websockets.ConnectionClosed:
print(f"Terminated")
break
print(f"< {name}")
greeting = f"Hello {name}!"
await websocket.send(greeting)
print(f"> {greeting}")
In the async
fun you can then await
any long running operation as suggested here.
You will however need to adapt both server and client side in the similar way. Your client also terminates after receiving the first message.