目标
- 理解客户端SUBSCRIBE MQTT服务器协议
- 理解客户端UNSUBSCRIBE MQTT服务器协议
准备
参见 “MQTT 实践” ,“MQTT-Java 连接协议” 完成测试工程配置
客户端连接MQTT服务器日志
2023-08-26 20:46:01:481 Send 包类型:SUBSCRIBE
2023-08-26 20:46:01:482 Send Message Header(二进制内容) : 10000010 00001100 00000000 00000001 00000000
2023-08-26 20:46:01:482 Send Message Header(字符串内容) : ���
2023-08-26 20:46:01:483 Send Message payload(二进制内容) : 00000000 00000110 01101000 01100001 01110010 01110110 01100101 01111001 00000001
2023-08-26 20:46:01:483 Send Message payload(字符串内容) : 内容长度=9,内容=�harvey
2023-08-26 20:46:01:484 Receive 包类型:SUBACK
2023-08-26 20:46:01:484 Receive Message Header(二进制内容) : 10010000 00000100 00000000 00000001 00000000
2023-08-26 20:46:01:484 Receive Message Header(字符串内容) : ���
2023-08-26 20:46:01:485 Receive Message payload(二进制内容) : 00000001
2023-08-26 20:46:01:485 Receive Message payload(字符串内容) :
MQTT 协议规范对照解析
MQTT 协议结构
整体结构 :固定头+可变头+内容
SUBSCRIBE协议详细解析
固定头
2023-08-26 20:46:01:482 Send Message Header(二进制内容) : 10000010 00001100 00000000 00000001 00000000
SUBSCRIBE协议的固定头值为: 100000010 xxxxxxxx
xxxxxxxx : 本次请求为 00001100 , 代表后边还有12个字节
可变头
| 第一个字节 | 第二个字节 | 第三个字节 |
|---|---|---|
| 00000000 | 00000001 | 00000000 |
| Figure 3-19 – SUBSCRIBE Variable Header example | Figure 3-19 – SUBSCRIBE Variable Header example | Figure 3-19 – SUBSCRIBE Variable Header example |
PAYLOAD
2023-08-26 20:46:01:483 Send Message payload(二进制内容) : 00000000 00000110 01101000 01100001 01110010 01110110 01100101 01111001 00000001
2023-08-26 20:46:01:483 Send Message payload(字符串内容) : 内容长度=9,内容=harvey
0000000 0000010 : 代表后后边有6个字节为订阅的主题内容
订阅主题内容表格
| 内容第一个字节 | 内容第二个字节 | 内容第三个字节 | 内容第四个字节 | 内容第五个字节 | 内容第六个字节 |
|---|---|---|---|---|---|
| 01101000 | 01100001 | 01110010 | 01110010 | 01100101 | 01111001 |
| h | a | r | v | e | y |
00000001 : 参见“3.8.3.1 Subscription Options”
| bit7 | bit6 | bit5 | bit4 | bit3 | bit2 | bit1 | bit0 |
|---|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
| reserved | reserved | the Retain Handling option | the Retain Handling option | the Retain As Published option | the No Local option | Maximum QoS field | Maximum QoS field |
SUBACK协议详细解析
固定头
2023-08-28 13:24:02:878 Receive Message Header(二进制内容) : 10010000 00000100 00000000 00000001 00000000
SUBACK协议的固定头值为: 10010000 xxxxxxxx
xxxxxxxx : 本次请求为 00000100 , 代表后边还有4个字节
可变头
| 第一个字节 | 第二个字节 | 第三个字节 |
|---|---|---|
| 00000000 | 00000001 | 00000000 |
| Figure 3-23 SUBACK packet Variable Header | Figure 3-23 SUBACK packet Variable Header | 3.9.2.1.1 Property Length |
PAYLOAD
2023-08-28 13:24:02:879 Receive Message payload(二进制内容) : 00000001
00000001 : 代表 “The subscription is accepted and the maximum QoS sent will be QoS 1. This might be a lower QoS than was requested”
UNSUBSCRIBE协议详细解析
根据SUBSCRIBE协议的分析过程,可自行尝试分析理解UNSUBSCRIBE协议