WebSocket waits for next async task to finish before sending a message #2644
-
DescriptionWhen sending multiple consecutive messages via a Steps to reproduce# server.py
from starlette.websockets import WebSocket
async def app(scope, receive, send):
websocket = WebSocket(scope=scope, receive=receive, send=send)
await websocket.accept()
await websocket.send_text('Hello world!')
status = await some_very_long_function()
await websocket.send_text(status)
await websocket.send_text('Hello world again!')
await websocket.close()
# lets say this runs for 2s
async def some_very_long_function():
# important: must NOT be an asyncio call
for i in range(300000000):
_ = i + i
return "done" # client.py
import asyncio
import websockets
async def receive():
async with websockets.connect('ws://localhost:8000') as websocket:
try:
while True:
message = await websocket.recv()
print(message)
except websockets.exceptions.ConnectionClosed:
print("Connection closed")
asyncio.get_event_loop().run_until_complete(receive())
Expected behaviour
Actual behaviour
Using asyncioIf we replace the blocking logic with # server.py
async def app(scope, receive, send):
websocket = WebSocket(scope=scope, receive=receive, send=send)
await websocket.accept()
await websocket.send_text('Hello world!')
await asyncio.sleep(1)
status = await some_very_long_function()
await websocket.send_text(status)
await websocket.send_text('Hello world again!')
await websocket.close() Results in:
|
Beta Was this translation helpful? Give feedback.
Answered by
Kludex
Jul 23, 2024
Replies: 1 comment
-
I cannot reproduce your experiment. I have the "expected" behavior here. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
Kludex
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I cannot reproduce your experiment. I have the "expected" behavior here.