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

Python客户端gRPC 'Socket closed'错误(grpc_status 14)求助

解决gRPC StatusCode.UNAVAILABLE(grpc_status 14)错误

问题代码

def run():
    try:
        channel = grpc.insecure_channel('api-auth.uid.ir')
        stub = session_api_pb2_grpc.SessionServiceStub(channel)
        response = stub.RegisterUserSession(
            session_api_pb2.RegisterUserSessionRequest(
                context={'requestHeader': {}, 'appInfo': {}, 'apiInfo': {}, 'panelInfo': {}},
                user={
                    'businessInformation': {
                        'projectName': 'Direct',
                        'businessId': '**************************',
                        'businessToken': '**************************'
                    },
                    'userInformation': {
                        'nationalId': '0874534879',
                        'nationalIdSerial': '1234567',
                        'sex': 1
                    }}))

        print(response)
    except Exception as e:
        print(e)

报错信息

<_InactiveRpcError of RPC that terminated with:
    status = StatusCode.UNAVAILABLE
    details = "failed to connect to all addresses; last error: UNAVAILABLE: Socket closed"
    debug_error_string = "UNKNOWN:Failed to pick subchannel {created_time:"2022-11-02T10:50:26.638744+03:30", children:[UNKNOWN:failed to connect to all addresses; last error: UNAVAILABLE: Socket closed {grpc_status:14, created_time:"2022-11-02T10:50:26.638736+03:30"}]}"
>

排查与解决步骤

  • 指定正确端口:grpc.insecure_channel默认使用50051端口,如果目标服务用的是其他端口,需要显式声明,比如grpc.insecure_channel('api-auth.uid.ir:8080'),先确认服务端对外暴露的端口信息。
  • 测试网络连通性:用telnet api-auth.uid.ir 50051或nc -zv api-auth.uid.ir 50051验证端口是否可访问,若不通,大概率是防火墙拦截、内网限制或地区网络封锁导致,需要调整网络环境。
  • 确认是否需要TLS加密:如果服务端要求加密连接,使用insecure_channel会直接失败,此时要切换为secure_channel并配置证书:
    import grpc
    from grpc import ssl_channel_credentials
    
    credentials = ssl_channel_credentials()
    channel = grpc.secure_channel('api-auth.uid.ir:443', credentials)
    
  • 校验请求参数合法性:部分服务会因参数格式错误主动关闭连接,检查context、user内的字段是否完全匹配服务端protobuf定义,比如sex的取值范围、空字典是否被允许。
  • 添加超时与调试日志:给channel设置连接超时,同时开启gRPC调试日志,便于定位问题:
    import logging
    logging.basicConfig()
    logging.getLogger('grpc').setLevel(logging.DEBUG)
    
    channel = grpc.insecure_channel(
        'api-auth.uid.ir',
        options=[
            ('grpc.connect_timeout_ms', 10000),
        ]
    )
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:15:37