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
相关产品推荐
相关产品推荐

