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

websockets.sync.client模块不存在及同步客户端实现错误求助

websockets基础客户端实现问题解析

问题本质

你遇到的问题核心是版本不兼容:

  • websockets.sync模块是websockets 11.0及以上版本才新增的同步客户端API,若安装版本低于11.0,会触发No module named 'websockets.sync'错误;
  • 旧版本(10.x及以下)的websockets.client.connect是异步API,不支持同步上下文管理器(with语句),因此会抛出TypeError。

解决方案

方案1:升级到最新版本(推荐)

执行命令将websockets升级至11.0及以上版本:

pip install --upgrade websockets

升级后,官方同步客户端代码可正常运行,只需删除无用的import asyncio:

from websockets.sync.client import connect

def hello():
    with connect("ws://localhost:8765") as websocket:
        websocket.send("Hello world!")
        message = websocket.recv()
        print(f"Received: {message}")

hello()

方案2:适配旧版本(不升级)

若需保留低版本,必须采用异步模式编写代码——旧版本的connect是异步上下文管理器,需配合async/await关键字:

import asyncio
from websockets.client import connect

async def hello():
    async with connect("ws://localhost:8765") as websocket:
        await websocket.send("Hello world!")
        message = await websocket.recv()
        print(f"Received: {message}")

asyncio.run(hello())

关于官方文档的说明

官方文档默认展示最新版本的API内容,若安装版本与文档版本不匹配,就会出现API不一致的情况。可在文档页面切换到对应版本,查看适配的代码示例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 09:20:33