Sending from a Thread #894
-
Versions
SituationI am currently trying to create a simple app which should take some data and send it to all the currently connected clients. As you can see in the source code below it creates an AsyncServer and attaches it to aiohttp. I then start the Server as a Thread and run a loop which sends a simple message to all clients. I have started the Server as a Thread as I need to gather the data from somewhere else, in this example it is emulated with the sendLoop function. In my case the client is a simple Socket.IO NodeJS client which only logs the received data. The NodeJS client is working so it is not the cause of my problem. import socketio, asyncio, logging
from aiohttp import web
from threading import Thread
logging.basicConfig(
filename="server.log",
format="%(asctime)s %(levelname)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
sio = socketio.AsyncServer(engineio_logger=True)
app = web.Application()
sio.attach(app)
@sio.event
async def connect(sid, environ):
await sio.send("hello client")
async def sendLoop():
"""Emulates a more complicated data retrieval process"""
i = 0
while True:
await sio.send(f"msg-{i}")
i += 1
await asyncio.sleep(1)
Thread(target=web.run_app, args=(app,), kwargs={"port": 8123}).start()
asyncio.run(sendLoop()) ProblemMy client connects without any problems and upgrades the connection from Long-Polling to Websockets. The "hello client" message is being emitted and received immediately, however the messages from the sendLoop are being received in blocks of variable time. Example: It almost always takes ~20s to receive the first few messages, when the client finally receives them they are there in <1s. Solution attempts
"Solution" that should not workAfter trying for a long time, I discovered that this problem is solved when using What can I do? LogServer log
Client
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The async server is not multi-threaded. If I understand your code correctly, you are running two asyncio loops here, which is not a supported workflow for this package. I would suggest that you move all your server code to the same loop. |
Beta Was this translation helpful? Give feedback.
The async server is not multi-threaded. If I understand your code correctly, you are running two asyncio loops here, which is not a supported workflow for this package. I would suggest that you move all your server code to the same loop.