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

Web3.py AsyncWeb3连接Infura Sepolia WebSocket端点失败求助

Web3.py AsyncWeb3连接Infura Sepolia WebSocket端点失败求助

我正在开发一个以太坊项目,需要通过Infura的WebSocket端点 wss://sepolia.infura.io/ws/v3/<PROJECT_ID> 连接Sepolia测试网。奇怪的是,这个端点在Postman里能正常建立连接,但用Web3.py的AsyncWeb3实现时却一直失败,报错信息如下:

ERROR:BlockchainLayer:Error connecting to WebSocket: Could not connect to: wss://sepolia.infura.io/ws/v3/<PROJECT_ID>. Retries exceeded max of 5.

因为Sepolia是PoA(权威证明)共识机制,我试过像HTTP连接那样注入ExtraDataToPOAMiddleware,但还是没用。HTTP端点的同款配置完全正常,唯独WebSocket连接死活连不上。

下面是我写的WebSocket连接相关代码:

async def connect_websocket(self):
    """
    Connects to the WebSocket endpoint using AsyncWeb3 and manages its context.
    """
    try:
        async with AsyncWeb3(WebSocketProvider(self.websocket_url)) as w3:
            # w3.middleware_onion.inject(ExtraDataToPOAMiddleware, layer=0)
            self.web3_ws = w3  
            if not await self.web3_ws.is_connected():
                raise ConnectionError(f"Failed to connect to WebSocket endpoint: {self.websocket_url}")
            self.logger.info(f"Connected to {self.network_name} network via WebSocket.")
    except ConnectionClosedError as e:
        self.logger.error(f"WebSocket connection closed: {e}")
    except Exception as e:
        self.logger.error(f"Error connecting to WebSocket: {e}")

我已经尝试过的解决方法

  • 用Postman验证WebSocket端点,能正常返回101 Switching Protocols响应
  • 反复确认API密钥和端点URL没有错误
  • 为PoA网络注入了ExtraDataToPOAMiddleware
  • 检查了Infura免费层的限流设置,确认没有超出限制
  • 将Web3.py升级到了最新版本

有没有大佬能给点思路,或者提供一个可用的实现示例呀?万分感谢!

备注:内容来源于stack exchange,提问作者seddouguim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 17:44:33