# 内部错误：gRPC：客户端流式写入失败：流已关闭，错误代码 2

- **ID:** `grpc/client-side-streaming-write-failure`
- **领域:** grpc
- **类别:** protocol_error
- **错误码:** `2`
- **验证级别:** ai_generated
- **修复率:** 82%

## 根因

gRPC 客户端流式 RPC 遇到写入失败，因为服务器因内部错误或超时而提前关闭流，导致客户端无法发送更多消息。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| gRPC v1.55.0 | active | — | — |
| gRPC v1.61.0 | active | — | — |
| gRPC v1.65.0 | active | — | — |

## 解决方案

1. ```
   为流式 RPC 实现带退避的重试循环：`for attempt in range(3): try: call.write(msg); break; except Exception: time.sleep(0.5*2**attempt)`
   ```
2. ```
   检查服务器的流超时时间，如果太低则增加：在服务器配置中设置 `grpc.max_connection_age` 或调整客户端超时以匹配。
   ```
3. ```
   添加客户端逻辑以检测流关闭并重新创建流：`if call.done(): call = stub.StreamingMethod()`
   ```

## 无效尝试

- **** — Retrying the entire streaming RPC from scratch may work but is inefficient and does not prevent the server-side issue. (60% 失败率)
- **** — Reducing the client's message size does not help if the server closes the stream due to a logic error or resource limit. (50% 失败率)
- **** — Ignoring the error and continuing to write to the closed stream will cause a panic or crash. (90% 失败率)
