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

如何在Python中过滤空WebSocket消息?现有过滤逻辑失效

问题:WebSocket接收消息时无法过滤空内容,持续输出空值

尝试过滤空消息但无效,打印消息长度也无法解决。调试发现空状态下的msg是WebSocket消息对象,无法获取长度、无可用打印内容,无法转为False,不等于'',甚至__str__()结果也不等于''。

相关代码

while True:
    try:
        async with websockets.connect('ws://localhost:8765') as websocket:
            msg= await asyncio.wait_for(websocket.recv(),.1)
            if msg:
                print(len(msg))
                terminal.text_area.insert(tk.END, msg)
    except Exception as e:
        print(e)
    app.update()
解决方法
  • 问题根源:websockets库的recv()方法不仅返回文本消息(字符串类型),还可能返回控制帧对象(比如Ping、Pong、Close帧)。这类对象是实例,布尔判断永远为True,会进入处理分支,但本身没有可显示的内容,导致看起来输出空值。
  • 过滤逻辑调整:先判断消息是否为字符串类型,再检查是否为空。修改判断条件为if isinstance(msg, str) and msg:,只处理有效文本消息。

修改后的代码

while True:
    try:
        async with websockets.connect('ws://localhost:8765') as websocket:
            msg= await asyncio.wait_for(websocket.recv(),.1)
            # 仅处理非空字符串类型的消息
            if isinstance(msg, str) and msg:
                print(len(msg))
                terminal.text_area.insert(tk.END, msg)
    except Exception as e:
        print(e)
    app.update()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 09:20:53