MQTT-Java SUBSCRIBE&UNSUBSCRIBE协议

129 阅读4分钟

目标

  • 理解客户端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 协议结构

整体结构 :固定头+可变头+内容 
协议-包结构.png

SUBSCRIBE协议详细解析

固定头

2023-08-26 20:46:01:482 Send Message Header(二进制内容) : 10000010 00001100 00000000 00000001 00000000 

协议-订阅请求.png

SUBSCRIBE协议的固定头值为: 100000010 xxxxxxxx
xxxxxxxx : 本次请求为 00001100 , 代表后边还有12个字节

可变头

第一个字节第二个字节第三个字节
000000000000000100000000
Figure 3-19 – SUBSCRIBE Variable Header exampleFigure 3-19 – SUBSCRIBE Variable Header exampleFigure 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

协议-SUBSCRIBE请求PAYLOAD.png

0000000 0000010 : 代表后后边有6个字节为订阅的主题内容

订阅主题内容表格

内容第一个字节内容第二个字节内容第三个字节内容第四个字节内容第五个字节内容第六个字节
011010000110000101110010011100100110010101111001
harvey

00000001 : 参见“3.8.3.1 Subscription Options”

bit7bit6bit5bit4bit3bit2bit1bit0
00000001
reservedreservedthe Retain Handling optionthe Retain Handling optionthe Retain As Published optionthe No Local optionMaximum QoS fieldMaximum QoS field

SUBACK协议详细解析

固定头

2023-08-28 13:24:02:878 Receive Message Header(二进制内容) : 10010000 00000100 00000000 00000001 00000000 

协议-suback.png SUBACK协议的固定头值为: 10010000 xxxxxxxx
xxxxxxxx : 本次请求为 00000100 , 代表后边还有4个字节

可变头

第一个字节第二个字节第三个字节
000000000000000100000000
Figure 3-23 SUBACK packet Variable HeaderFigure 3-23 SUBACK packet Variable Header3.9.2.1.1 Property Length

PAYLOAD

2023-08-28 13:24:02:879 Receive Message payload(二进制内容) : 00000001 

协议-subackpayload.png

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协议