You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Asyncio创建的socket监听任务未执行,主事件循环正常运行

问题分析与解决

你的代码里client_socket任务没执行的核心原因是**main_loop里的while True是无限同步循环,完全占用了事件循环线程,没给其他任务留执行机会**。asyncio是单线程协程模型,必须通过await让出控制权,事件循环才能切换到其他任务。

修复步骤:

  1. 给主循环添加控制权让出语句
    在main_loop的循环里加入await asyncio.sleep(0),哪怕是0秒的sleep,也能让事件循环调度其他任务:

    async def main_loop(self):
        self.queue = asyncio.Queue()
        # 用asyncio.create_task更简洁,效果和get_event_loop().create_task一致
        asyncio.create_task(self.client_socket())
        while True:
            print("Game Loop")
            # 让出控制权,让其他协程执行
            await asyncio.sleep(0)
    
  2. 修正端口参数类型
    asyncio.open_connection的port要求是整数,你传的字符串"55555"会导致连接失败,改成:

    reader, writer = await asyncio.open_connection(host="127.0.0.1", port=55555)
    
  3. 确保数据发送完成
    调用writer.write后加await writer.drain(),保证数据被真正发送出去:

    writer.write("CONNECT".encode("utf-8"))
    await writer.drain()
    

完整修正后的代码片段:

async def main_loop(self):
    self.queue = asyncio.Queue()
    asyncio.create_task(self.client_socket())
    while True:
        print("Game Loop")
        await asyncio.sleep(0)

async def client_socket(self):
    print("Client socket online")
    try:
        reader, writer = await asyncio.open_connection(host="127.0.0.1", port=55555)
        writer.write("CONNECT".encode("utf-8"))
        await writer.drain()
        while True:
            data = await reader.read(1024)
            if not data:
                continue
            # 可在此处理收到的数据
            print(f"Received: {data.decode('utf-8')}")
    except Exception as e:
        print(f"Socket error: {e}")

内容的提问来源于stack exchange,提问作者jaal kamza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 04:30:53