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

Python websockets 9.1连接被HTTP拒绝时未立刻返回而是超时问题咨询

问题根因

你使用的websockets 9.1版本存在握手逻辑缺陷:当服务端在握手阶段返回非101的HTTP响应(比如403鉴权失败)时,客户端不会主动终止握手流程,会一直等待直到默认的10秒超时阈值触发后才抛出异常。

实现方案

方案1:升级websockets库到10.0及以上版本

该方案改造成本最低,websockets 10.0及以上版本已经官方修复了该问题,握手阶段收到非101状态码会立刻抛出InvalidStatusCode异常,无需等待超时,同时你配置的长超时规则可以正常生效,覆盖慢速连接场景。
升级命令:
pip install websockets>=10.0

方案2:9.1版本兼容方案(无法升级依赖时使用)

如果因为业务约束必须使用9.1版本,可以自定义客户端协议类,重写握手响应处理逻辑,主动识别非101状态码并立刻抛出异常,无需等待超时触发。

自定义协议代码

import websockets
from websockets.exceptions import InvalidStatusCode
from websockets.client import WebSocketClientProtocol

class FastFailWebSocketClientProtocol(WebSocketClientProtocol):
    async def process_response(self, response):
        # 收到非握手成功的状态码直接抛出异常,终止握手流程
        if response.status_code != 101:
            raise InvalidStatusCode(response.status_code, response.headers)
        # 正常101响应走原有逻辑
        await super().process_response(response)

连接调用示例

async with websockets.connect(
    "ws://wrongUser:andPassword@localhost",
    max_size=2**28,
    subprotocols=["SomeApi"],
    create_protocol=FastFailWebSocketClientProtocol,
    # 保留原有长超时配置即可,慢速连接场景仍会按该阈值判断超时
    open_timeout=30
) as ws:
    # 正常连接后的业务逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:06:04