SocketIO后台任务未运行:多人在线游戏服务端代码问题排查
问题分析与解决:SocketIO服务端后台任务无法运行
问题定位
你的后台任务无法运行的核心原因有两个:
- 阻塞式sleep的误用:异步函数
background_thread里使用了同步阻塞的time.sleep(5),这会直接卡住整个异步事件循环,导致后台任务无法正常循环执行,甚至影响服务整体响应。 - 异步方法未加await:
sio.emit是异步方法,在异步函数中必须用await等待其执行完成,否则会导致协程无法正确调度。 - 同步事件处理函数不匹配配置:初始化
AsyncServer时指定了async_handlers=True,但connect、disconnect是同步函数,会导致这些事件处理无法被正确触发(虽不是后台任务失效的直接原因,但属于潜在问题)。
修复后的代码
import socketio import asyncio from aiohttp import web sio = socketio.AsyncServer(async_mode='aiohttp', cors_allowed_origins='*', async_handlers=True) app = web.Application() sio.attach(app) @sio.on('connect') async def connect(sid, environ): print("connected: ", sid) @sio.on('disconnect') async def disconnect(sid): print('disconnect ', sid) async def background_thread(): while True: print("here") await sio.emit('message', {'data': 'Server generated event'}) await asyncio.sleep(5) if __name__ == '__main__': print ("Starting server") sio.start_background_task(background_thread) web.run_app(app, port=3000)
关键修改说明
- 替换
time.sleep(5)为await asyncio.sleep(5):异步睡眠不会阻塞事件循环,让后台任务能持续循环,同时不影响服务的其他异步操作。 - 给
sio.emit加上await:确保异步发射事件的操作被正确调度执行。 - 将
connect、disconnect改为异步函数:匹配async_handlers=True的配置,保证客户端连接/断开事件能被正常处理。
内容的提问来源于stack exchange,提问作者Sajjad Ahmed Shaaz
相关产品推荐
相关产品推荐

