# MQTT CONNACK 返回标识符被拒绝 (0x02) 或服务器不可用 (0x03)

- **ID:** `communication/mqtt-publish-identifier-in-use`
- **领域:** communication
- **类别:** auth_error
- **错误码:** `0x02`
- **验证级别:** ai_generated
- **修复率:** 83%

## 根因

MQTT 代理拒绝客户端连接，因为客户端标识符已被使用且未设置清除会话，或代理的连接数已达上限。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Mosquitto 2.0.15 | active | — | — |
| EMQX 5.3 | active | — | — |
| AWS IoT Core | active | — | — |
| Paho MQTT 1.6 | active | — | — |

## 解决方案

1. ```
   在 CONNECT 数据包中将清除会话标志设置为 true，例如在 Paho Python 中：`client.connect(broker, port, keepalive=60, clean_session=True)`。
   ```
2. ```
   为每个连接生成唯一的客户端 ID，使用 UUID 或设备特定标识符，例如 `client_id = f"device-{uuid.uuid4()}"`。
   ```
3. ```
   增加代理上的最大并发连接数，例如在 Mosquitto 中：在 `mosquitto.conf` 中添加 `max_connections 1000`。
   ```

## 无效尝试

- **Reconnect with the same client ID repeatedly without changing anything** — The broker continues to reject the same client ID if the session is still active or limit persists. (85% 失败率)
- **Disable all security settings on the broker (e.g., remove authentication)** — May violate security policies and does not address the client ID conflict or connection limit. (90% 失败率)
- **Use a random client ID on every reconnect without setting clean session** — Random IDs may still conflict if not unique; without clean session, the broker retains state for each ID, potentially exhausting resources. (70% 失败率)
