SUBSCRIBE / SUBACK / UNSUBSCRIBE / UNSUBACK 报文格式
OASIS MQTT 5.0:§3.8 SUBSCRIBE、§3.9 SUBACK、§3.10 UNSUBSCRIBE、§3.11 UNSUBACK
Topic / 通配符 / 共享订阅概念见:01-主题与发布订阅模型.md
1. SUBSCRIBE(§3.8)
1.1 Fixed Header
| Type | Flags |
|---|---|
8 |
必须 0010(bit1=1) |
1.2 Variable Header
1 | Packet Identifier → Properties(5.0) |
常见 Properties:
| 属性 | 作用 |
|---|---|
| Subscription Identifier | 订阅标识;后续 PUBLISH 可带回,便于 Client 分流回调 |
| User Property | 自定义 |
1.3 Payload:订阅列表
由一个或多个订阅组成,每项:
1 | ┌─────────────────────┬──────────────────┐ |
Subscription Options(1 字节,5.0)
1 | bit7-6 bit5-4 bit3 bit2 bit1-0 |
| 字段 | 含义 |
|---|---|
| Maximum QoS | Client 愿接受的最大 QoS(0/1/2) |
| No Local | 1=不接收自己在同连接上发布的消息 |
| Retain As Published | 转发时保留原消息 RETAIN 标志 |
| Retain Handling | 0=发送保留消息;1=仅新订阅发送;2=不发送保留消息 |
3.1.1:Payload 每项仅为 Topic Filter + Requested QoS(1 字节,高 6 位必须为 0)。
1.4 Topic Filter 规则(摘要)
- 可含
+/#通配符(#须单独一层且在末尾) - MQTT 5 共享订阅:
$share/{ShareName}/{TopicFilter} - 非法 Filter → Server 在 SUBACK 返回失败 Reason,或协议错误处理
2. SUBACK(§3.9)
2.1 Fixed Header
Type=9,Flags=0000。
2.2 Variable Header
1 | Packet Identifier → Properties(5.0)(Reason String、User Property…) |
2.3 Payload:Reason Code 列表
- 按订阅顺序一一对应 SUBSCRIBE Payload 中的每一项
- 每个 1 字节
| Reason(例) | 含义 |
|---|---|
0x00 |
Granted QoS 0 |
0x01 |
Granted QoS 1 |
0x02 |
Granted QoS 2 |
0x80 |
Unspecified error |
0x83 |
Implementation specific error |
0x87 |
Not authorized |
0x8F |
Topic Filter invalid |
0x91 |
Packet Identifier in use |
0x97 |
Quota exceeded |
0x9E |
Shared Subscriptions not supported |
0xA1 |
Subscription Identifiers not supported |
0xA2 |
Wildcard Subscriptions not supported |
要点:Granted QoS 可以低于 Requested QoS;Client 必须以 SUBACK 为准。
3.1.1:Payload 为 Return Code(0x00/0x01/0x02/0x80)。
3. UNSUBSCRIBE(§3.10)
3.1 Fixed Header
Type=10,Flags=0010。
3.2 Variable Header
Packet Identifier + Properties(5.0)。
3.3 Payload
一个或多个 Topic Filter(UTF-8 String),无 Options 字节。
4. UNSUBACK(§3.11)
4.1 Fixed Header
Type=11,Flags=0000。
4.2 Variable Header
Packet Identifier + Properties(5.0)。
4.3 Payload(MQTT 5)
每个 Topic Filter 对应 1 字节 Reason Code,例如:
| Code | 含义 |
|---|---|
0x00 |
Success |
0x11 |
No subscription existed |
0x80 |
Unspecified error |
0x87 |
Not authorized |
0x8F |
Topic Filter invalid |
3.1.1:UNSUBACK 仅有 Packet Identifier,无 Payload Reason 列表。
5. 时序示例
1 | Client ── SUBSCRIBE (P=10, filter=siteA/+/state, maxQoS=1) ──▶ Server |
正在加载留言…