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

Python WebSocket客户端按不同间隔周期性发消息报错问题

WebSocket客户端多间隔发送消息的问题修复

报错原因解析

  • RuntimeError: cannot call recv while another coroutine is already waiting for the next message:同一个WebSocket连接被两个协程同时执行await websocket.recv(),websockets库不允许并发调用接收方法,会导致消息处理逻辑冲突。
  • RuntimeError: 未收到或发送关闭帧:注释一个recv()后,服务器返回的响应未被全部处理,或连接因消息处理不完整被异常终止,触发关闭帧校验错误。

修正方案

单独用一个协程处理所有消息接收,发送协程仅负责按间隔发送消息,避免并发调用recv()。

修正后的代码

import asyncio
import websockets

IP = "你的服务器IP"
PORT = 你的端口号

async def receive_messages(websocket):
    # 单独处理所有服务器响应,避免并发recv冲突
    while True:
        try:
            response = await websocket.recv()
            print(f"收到服务器响应: {response}")
        except websockets.exceptions.ConnectionClosed:
            print("连接已关闭")
            break

async def send_first_message(websocket):
    while True:
        await websocket.send("FIRST MESSAGE")
        await asyncio.sleep(2)

async def send_second_message(websocket):
    while True:
        await websocket.send("SECOND MESSAGE")
        await asyncio.sleep(5)

async def main():
    async with websockets.connect(f"ws://{IP}:{PORT}") as websocket:
        # 启动独立的消息接收协程
        asyncio.create_task(receive_messages(websocket))
        # 并行运行两个发送协程
        await asyncio.gather(
            send_first_message(websocket),
            send_second_message(websocket)
        )

asyncio.run(main())

代码说明

  1. receive_messages协程单独接管所有服务器响应的接收工作,彻底避免多个协程同时调用recv()的冲突。
  2. 两个发送协程仅专注于按指定间隔发送消息,不再各自处理接收逻辑。
  3. 使用asyncio.gather实现两个发送协程的并行执行,保证时间间隔的准确性。
  4. 增加连接关闭异常捕获,让程序能优雅处理连接断开场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:40:29