Events not handled concurrently #1085
Replies: 2 comments 2 replies
-
How familiar are you with writing asynchronous code with asyncio? The code that you have written is synchronous, it is invalid for asyncio. First of all, you cannot use |
Beta Was this translation helpful? Give feedback.
-
Thanks for your response, Miguel. I'm familiar with the basics of asyncio, but there's a lot left I could learn. FastAPI allows the path operation functions to be sync or async, running the path operation function in a new thread when it's a synchronous function. I guess I was hoping things would just work, allowing subsequent emitted events from a single client to run in separate threads as well, but that may not be possible with AsyncServer, and I'm assuming socketio.Server isn't compatible with FastAPI since FastAPI implements the ASGI spec. If anyone else comes across this, I wanted to point out that the following examples do work as I originally intended and might be helpful. # scratch_server.py
import asyncio
import time
import socketio
from fastapi import FastAPI
app = FastAPI()
app.sio = socketio.AsyncServer(
async_mode="asgi",
cors_allowed_origins="*"
)
app.mount(
path="/ws",
app=socketio.ASGIApp(
socketio_server=app.sio,
socketio_path="socket.io",
),
)
@app.sio.on("ping")
async def handle_ping(sid, *args, **kwargs):
print("got ping")
# can replace time.sleep with any non-async IO-bound function, and it'll run in a separate thread. Be careful with race conditions.
await asyncio.get_event_loop().run_in_executor(None, time.sleep, 1)
print("returning pong")
return "pong"
# also works as originally intended
@app.sio.on("ping2")
async def handle_ping2(sid, *args, **kwargs):
print("got ping2")
await asyncio.sleep(1)
print("returning pong2")
return "pong2" # scratch_client.py
import socketio
sio = socketio.Client()
sio.connect(
"ws://localhost:8000", socketio_path="/ws/socket.io", transports=["websocket"]
)
for i in range(10):
sio.emit("ping")
for i in range(10):
sio.emit("ping2") |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
My issue is very similar to this old issue #90, but I'm using uvicorn/FastAPI instead. I expect the events to be handled concurrently, but they seem to be handled synchronously.
To Reproduce
I launch the server with
uvicorn scratch_server:app --workers 10
. scratch_client.py takes about 10s to run and the output is:I expect the events to be handled concurrently and so I expect scratch_client.py to run in about 1s and that I'd see 10 "got ping" logs followed by 10 "returning pong" logs. Apologies if this is user error, as I am new to this, but any guidance is greatly appreciated 🙏 .
Beta Was this translation helpful? Give feedback.
All reactions