MQTT-3.1.1-CN 1
MQTT Protocol 3.1.1 Chinese version
OASIS Standard
2014 year 10 month 29 day
specification link
current version:
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.doc (Authoritative)
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.pdf
previousversion:
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/cos01/mqtt-v3.1.1-cos01.doc (Authoritative)
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/cos01/mqtt-v3.1.1-cos01.html
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/cos01/mqtt-v3.1.1-cos01.pdf
latest version:
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.doc (Authoritative)
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.pdf
Technical CommitteeCommittee:
Structured Information Standardspromoting organization MQTT Technical Committee
Chair:
Raphael·J· Cohen (raphael.cohn@stormmq.com), Individual
Richard·J· Koppen (coppen@uk.ibm.com), IBM
Edit:
Andrew Banks (Andrew_Banks@uk.ibm.com), IBM
Rahul Gupta (rahul.gupta@us.ibm.com), IBM
Related documentation:
This specification is related to this:
MQTT and NIST network securityFramework 1.0 Version. Editors are Jeff Brown and Louis·Philip· Lamule. Latest version
This: http://docs.oasis-open.org/mqtt/mqtt-nist-cybersecurity/v1.0/mqtt-nist-cybersecurity-
v1.0.html.
Summary:
MQTT is aClient serviceThe development of the end architecturecloth/subscription modelthe message transport protocol.Its design philosophy islightweight,Open、
Simple、Specification,ThereforeEasy to implement.These characteristics makeIt is useful for many scenariosis a very good choice, includingconstrained environments such as
Machine-to-machine communicationBelieve (M2M)and IoTnetwork environment (IoT),TheseThe scenario requires very little codecode encapsulation or networknetwork bandwidth
Very expensive.
this protocolRunIn TCP/IP, orOthers provide ordered, reliable, bidirectionalconnected network connectionon. It has the followingthe following features:
using publish/SubscriptionMessage pattern, providinga one-to-many message distributionand between applicationsdecoupling.
Message transmission does not requireknow the payload content。
Provides three levels ofQuality of Service:.
MQTT-3.1.1-CN 2
“at most once”, as much as the operating environment canprovided maximum effortto deliver messages.Messages may be lost.For example,This
The level can be used forEnvironmental sensor data,Single data lossLoss doesn't matter,becausewill soonSend again.
“at least once”, ensuring that messages can arriveReach,ButMay repeat.
“only once”,WarrantyA message is delivered only once. For example,ThisThe level can be used inA billing systemin, if here
Message duplication or losswill lead to incorrectthe fee.
Very small transmission overheadand protocol data exchangeexchange, minimize to the greatest extentnetwork traffic
Abnormal connection disconnection occursWhen it occurs, can notifyto relevant parties.
state:
This document was last OASIS members inThe final date indicated aboverevised or approved.the approval level alsoListed above.if
To view this document's mostthe new revision, pleaseCheck the above
latest version
Location. Produced by the technical committeeother revisions andother technologies
Technical documents are all listed hereInside:https://www.oasis-
open.org/committees/tc_home.php?wg_abbrev=mqtt#technical 。
Technical committee memberscomments on this specificationDiscussion should be sent to the technical committeecommittee's mailing listTable. Others should sendcomments to the technical committee
The committee's public commentslist, methodis pointClick the technical committeeof the association's website send comments button,The web address is
https://www.oasis-open.org/committees/mqtt/ 。
About implementing this specificationessential taskswhether any patent has been disclosed,and other specializedinformation related to the license termsbreath, please refer to the tech
Technical committee website'sIntellectual property section((https://www.oasis-open.org/committees/mqtt/ipr.php)。
reference formatForm:
When citing this specification, shouldshould use the followingCitation format:
[mqtt-v3.1.1]
MQTT Version 3.1.1. Edited by Andrew Banks and Rahul Gupta. 29 October 2014. OASIS
Standard. http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html. Latest version:
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html.
MQTT-3.1.1-CN 3
document links
MQTT Protocol 3.1.1 Chinesetranslation project
MQTT Protocol 3.1.1 Chinese version PDF
revision history
edition book
day period
release notes
1.0.0
2015-07-30
Translate all text,Complete the initial review, publicly released as thefirst edition
1.0.1
2015-10-22
Revise several typographical errors,supplement several untranslatedtranslated text
closefor the translator
GitHub
Blog
Email
MQTT-3.1.1-CN 4
Directory
1 Overview ...................................................................................................................................................... 8
1.1 MQTT Organizational structure of the protocol ........................................................................................................................ 8
1.2 Term ..................................................................................................................................................... 8
1.3 normative references .............................................................................................................................................. 9
1.4 non-normative referencesuse ........................................................................................................................................ 10
1.5 data representation ............................................................................................................................................ 12
1.5.1 binarybit .................................................................................................................................... 12
1.5.2 Integervalue .................................................................................................................................... 12
1.5.3 UTF-8 Encoded string ..................................................................................................................... 12
1.6 editorial conventions ............................................................................................................................................ 13
2 MQTT control packetmessage format ........................................................................................................................... 14
2.1 MQTT Structure of control messages ...................................................................................................................... 14
2.2 fixed header ............................................................................................................................................ 14
2.2.1 MQTT Types of control messages .............................................................................................................. 14
2.2.2 Flags ........................................................................................................................................... 15
2.2.3 remaininglength .................................................................................................................................... 16
2.3 variable header ............................................................................................................................................ 17
2.3.1 messageIdentifiers ................................................................................................................................. 17
2.4 payload ............................................................................................................................................ 19
3 MQTT control packettext .................................................................................................................................. 20
3.1 CONNECT – Connect to the server .................................................................................................................. 20
3.1.1 Fixedheader .................................................................................................................................... 20
3.1.2 variableheader .................................................................................................................................... 20
3.1.3 validpayload .................................................................................................................................... 26
3.1.4 response ........................................................................................................................................... 27
3.2 CONNACK – confirmconnection requestFind .............................................................................................................. 28
3.2.1 Fixedheader .................................................................................................................................... 28
3.2.2 variableheader .................................................................................................................................... 28
3.2.3 validpayload .................................................................................................................................... 30
3.3 PUBLISH – publish message ........................................................................................................................ 30
3.3.1 Fixedheader .................................................................................................................................... 30
3.3.2 variableheader .................................................................................................................................... 32
3.3.3 validpayload .................................................................................................................................... 33
3.3.4 response ........................................................................................................................................... 33
3.3.5 action ........................................................................................................................................... 33
3.4 PUBACK –publish acknowledgment .......................................................................................................................... 33
3.4.1 Fixedheader .................................................................................................................................... 33
3.4.2 variableheader .................................................................................................................................... 34
3.4.3 validpayload .................................................................................................................................... 34
MQTT-3.1.1-CN 5
3.4.4 action ........................................................................................................................................... 34
3.5 PUBREC – emitpublish received (QoS 2, firststep) ........................................................................................ 34
3.5.1 Fixedheader .................................................................................................................................... 34
3.5.2 variableheader .................................................................................................................................... 34
3.5.3 validpayload .................................................................................................................................... 35
3.5.4 action ........................................................................................................................................... 35
3.6 PUBREL – publishrelease (QoS 2, secondstep) ......................................................................................... 35
3.6.1 Fixedheader .................................................................................................................................... 35
3.6.2 variableheader .................................................................................................................................... 35
3.6.3 validpayload .................................................................................................................................... 36
3.6.4 action ........................................................................................................................................... 36
3.7 PUBCOMP – emitpublish complete (QoS 2, step 3) ..................................................................................... 36
3.7.1 Fixedheader .................................................................................................................................... 36
3.7.2 variableheader .................................................................................................................................... 36
3.7.3 validpayload .................................................................................................................................... 36
3.7.4 action ........................................................................................................................................... 36
3.8 SUBSCRIBE - subscription topic ................................................................................................................... 37
3.8.1 Fixedheader .................................................................................................................................... 37
3.8.2 variableheader .................................................................................................................................... 37
3.8.3 validpayload .................................................................................................................................... 37
3.8.4 response ........................................................................................................................................... 39
3.9 SUBACK – subscription acknowledgment ......................................................................................................................... 40
3.9.1 Fixedheader .................................................................................................................................... 40
3.9.2 variableheader .................................................................................................................................... 40
3.9.3 validpayload .................................................................................................................................... 41
3.10 UNSUBSCRIBE –CancelSubscription ............................................................................................................ 41
3.10.1 fixed header .................................................................................................................................. 42
3.10.2 variable header .................................................................................................................................. 42
3.10.3 payload .................................................................................................................................. 42
3.10.4 response ......................................................................................................................................... 43
3.11 UNSUBACK – Cancel subscriptionacknowledgment .......................................................................................................... 43
3.11.1 fixed header .................................................................................................................................. 44
3.11.2 variable header .................................................................................................................................. 44
3.11.3 payload .................................................................................................................................. 44
3.12 PINGREQ – heartbeat request ..................................................................................................................... 44
3.12.1 fixed header .................................................................................................................................. 44
3.12.2 variable header .................................................................................................................................. 45
3.12.3 payload .................................................................................................................................. 45
3.12.4 response ......................................................................................................................................... 45
3.13 PINGRESP – heartbeat response ................................................................................................................... 45
3.13.1 fixed header .................................................................................................................................. 45
MQTT-3.1.1-CN 6
3.13.2 variable header .................................................................................................................................. 45
3.13.3 payload .................................................................................................................................. 45
3.14 DISCONNECT –disconnect............................................................................................................... 45
3.14.1 fixed header .................................................................................................................................. 46
3.14.2 variable header .................................................................................................................................. 46
3.14.3 payload .................................................................................................................................. 46
3.14.4 response ......................................................................................................................................... 46
4 operational behavior ............................................................................................................................................. 47
4.1 state storage ............................................................................................................................................ 47
4.1.1 non-normativeexample ................................................................................................................................. 47
4.2 Network Connection ............................................................................................................................................ 47
4.3 Quality of ServiceLevels and protocol flows .................................................................................................................. 48
4.3.1 QoS 0:at mostdeliver once .................................................................................................................. 48
4.3.2 QoS 1: at leastdeliver once ................................................................................................................. 48
4.3.3 QoS 2: only partsend once .................................................................................................................... 49
4.4 message distributionRetry .................................................................................................................................... 51
4.5 message received ............................................................................................................................................ 51
4.6 message ordering ............................................................................................................................................ 51
4.7 topic name andTopic filter ......................................................................................................................... 52
4.7.1 topicwildcard ................................................................................................................................. 52
4.7.2 with$opentopic of the header ........................................................................................................................... 53
4.7.3 topicSemantics and usage ......................................................................................................................... 53
4.8 Error Handling ............................................................................................................................................ 54
5 security .................................................................................................................................................... 55
5.1 Overview ................................................................................................................................................... 55
5.2 MQTT Solution: secure andauthentication ........................................................................................................... 55
5.3 lightweightEncryption and constrained devices .................................................................................................................. 55
5.4 implementation notesitem .................................................................................................................................... 55
5.4.1 clientEndpoint authentication ......................................................................................................................... 56
5.4.2 clientclient authorization ................................................................................................................................. 56
5.4.3 ServicesEndpoint authentication ......................................................................................................................... 56
5.4.4 controlmessages and application messagesMessage integrity .................................................................................................... 56
5.4.5 controlmessages and application messagesMessage confidentiality .................................................................................................... 56
5.4.6 Messagenon-repudiation of transmissionauthenticity .............................................................................................................. 56
5.4.7 detectionclient and serverclient spoofing ....................................................................................................... 57
5.4.8 detectionabnormal behavior ............................................................................................................................. 57
5.4.9 othersecurity precautionsitem .................................................................................................................. 57
5.4.10 Usage SOCKS broker .................................................................................................................... 58
5.4.11 security configurationFile ........................................................................................................................... 58
6 Usage WebSocket dofor the network layer .............................................................................................................. 59
6.1 IANA Noteitem .................................................................................................................................. 59
MQTT-3.1.1-CN 7
7 consistency ................................................................................................................................................. 60
7.1 consistency goalmark ........................................................................................................................................ 60
7.1.1 MQTT Server-side ............................................................................................................................. 60
7.1.2 MQTT client ............................................................................................................................. 60
appendix B Mandatory normative statement (non-normativenormative) ............................................................................................................. 62
MQTT-3.1.1-CN 8
1 Overview
1.1 MQTT cooperateprotocol organizational structure
This specification is divided into sevenchapters:
Chapter 1 - Introduction
Chapter 2 – MQTT control message format
Chapter 3 – MQTT control packet
Chapter 4 – OperationBehavior
Chapter 5 – security
Chapter 6 – Usage WebSocket As a network transport layer t
Chapter 7 – consistentsecurity objectives
1.2 Term
Used in this specificationKeywords Required MUST,cannot MUST NOT,Requirement REQUIRED,will SHALL,Will not SHALL
NOT,should SHOULD,should not SHOULD NOT,Recommended RECOMMENDED,Yes MAY,Optional OPTIONAL
all according to IETF RFC 2119 [RFC2119] description inexplain.
Network Connection(Network Connection):
MQTT usedUnderlying transport protocolProtocol infrastructure。
The client uses it to connect to the server.
It provides ordered,reliableof,Bidirectional byte stream transport.
see examples 4.2 section.
application message(Application Message):
MQTT protocol communicationTransmit over the networkApplication data.application messages through MQTT when transmitted, theyAssociated serviceQuality of Service (QoS) andtopic
(Topic)。
client(Client):
Usage MQTT of a program or device.clients always connectover the network to connect toServer. ItYes
Publish application messages to other relatedthe client..
SubscriptionwithrequestAccepts the relevant application messages
Unsubscribe to removereceive application messagesrequest.
Disconnect from the serverconnect.
Server-side(Server):
a program or device, as the sending messagemessage's client andthe client requesting the subscriptionintermediary between. The serverserver
Accept network connections from clients.
Accept client publishapplication message
MQTT-3.1.1-CN 9
Process client's subscriptionsubscribe and unsubscriberequest.
forwardApply messages to conformingcomponent's clientSubscription。
Subscription(Subscription):
Subscription contains a topicTopic filter (Topic Filter) anda largest serverQuality of Service (QoS) level. Subscription with a singleSession
(Session) relatedconnection. Sessions canContains more than one subscription. SessionEach subscription has adifferent topics throughfilter.
topic name (Topic Name):
Attached to the application messagea label on, known to the server and with the subscriptionsubscription matching. The server sendsthe application message's onea copy to each matching
of the client subscription.
topic filterfilter (Topic Filter:):
one included in the subscriptionexpression, usedfor representing relatedone or more mastersTopic. Topic filters canUse wildcards.
Session(Session):
client and serverstate exchange betweeninteraction. Some sessions last whenlength and networklike a network connection,others can be inclient and server multiple
a continuous network connectioninterval extension.
control packet(MQTT Control Packet):
sent over the network connectionthe transmitted information datapackage.MQTT The specification defines fourteendifferent types of control messagestext,whereone (PUBLISH report
message) used to transmit applicationuse message.
1.3 SpecificationReference
[RFC2119]
Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, March
1997.
http://www.ietf.org/rfc/rfc2119.txt
[RFC3629]
Yergeau, F., "UTF-8, a transformation format of ISO 10646", STD 63, RFC 3629, November 2003
http://www.ietf.org/rfc/rfc3629.txt
[RFC5246]
Dierks, T. and E. Rescorla, "The Transport Layer Security (TLS) Protocol Version 1.2", RFC 5246, August
2008.
http://www.ietf.org/rfc/rfc5246.txt
[RFC6455]
Fette, I. and A. Melnikov, "The WebSocket Protocol", RFC 6455, December 2011.
http://www.ietf.org/rfc/rfc6455.txt
[Unicode]
The Unicode Consortium. The Unicode Standard.
http://www.unicode.org/versions/latest/
MQTT-3.1.1-CN 10
1.4 Non-normative reference
[RFC793]
Postel, J. Transmission Control Protocol. STD 7, IETF RFC 793, September 1981.
http://www.ietf.org/rfc/rfc793.txt
[AES]
Advanced Encryption Standard (AES) (FIPS PUB 197).
http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
[DES]
Data Encryption Standard (DES).
http://csrc.nist.gov/publications/fips/fips46-3/fips46-3.pdf
[FIPS1402]
Security Requirements for Cryptographic Modules (FIPS PUB 140-2)
http://csrc.nist.gov/publications/fips/fips140-2/fips1402.pdf
[IEEE 802.1AR]
IEEE Standard for Local and metropolitan area networks - Secure Device Identity
http://standards.ieee.org/findstds/standard/802.1AR-2009.html
[ISO29192]
ISO/IEC 29192-1:2012 Information technology -- Security techniques -- Lightweight cryptography -- Part
1: General
http://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=56425
[MQTT NIST]
MQTT supplemental publication, MQTT and the NIST Framework for Improving Critical Infrastructure
Cybersecurity
http://docs.oasis-open.org/mqtt/mqtt-nist-cybersecurity/v1.0/mqtt-nist-cybersecurity-v1.0.html
[MQTTV31]
MQTT V3.1 Protocol Specification.
http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html
[NISTCSF]
Improving Critical Infrastructure Cybersecurity Executive Order 13636
http://www.nist.gov/itl/upload/preliminary-cybersecurity-framework.pdf
[NIST7628]
NISTIR 7628 Guidelines for Smart Grid Cyber Security
http://www.nist.gov/smartgrid/upload/nistir-7628_total.pdf
[NSAB]
NSA Suite B Cryptography
http://www.nsa.gov/ia/programs/suiteb_cryptography/
MQTT-3.1.1-CN 11
[PCIDSS]
PCI-DSS Payment Card Industry Data Security Standard
https://www.pcisecuritystandards.org/security_standards/
[RFC1928]
Leech, M., Ganis, M., Lee, Y., Kuris, R., Koblas, D., and L. Jones, "SOCKS Protocol Version 5", RFC
1928, March 1996.
http://www.ietf.org/rfc/rfc1928.txt
[RFC4511]
Sermersheim, J., Ed., "Lightweight Directory Access Protocol (LDAP): The Protocol", RFC 4511, June
2006.
http://www.ietf.org/rfc/rfc4511.txt
[RFC5077]
Salowey, J., Zhou, H., Eronen, P., and H. Tschofenig, "Transport Layer Security (TLS) Session
Resumption without Server-Side State", RFC 5077, January 2008.
http://www.ietf.org/rfc/rfc5077.txt
[RFC5280]
Cooper, D., Santesson, S., Farrell, S., Boeyen, S., Housley, R., and W. Polk, "Internet X.509 Public Key
Infrastructure Certificate and Certificate Revocation List (CRL) Profile", RFC 5280, May 2008.
http://www.ietf.org/rfc/rfc5280.txt
[RFC6066]
Eastlake 3rd, D., "Transport Layer Security (TLS) Extensions: Extension Definitions", RFC 6066, January
2011.
http://www.ietf.org/rfc/rfc6066.txt
[RFC6749]
Hardt, D., Ed., "The OAuth 2.0 Authorization Framework", RFC 6749, October 2012.
http://www.ietf.org/rfc/rfc6749.txt
[RFC6960]
Santesson, S., Myers, M., Ankney, R., Malpani, A., Galperin, S., and C. Adams, "X.509 Internet Public
Key Infrastructure Online Certificate Status Protocol - OCSP", RFC 6960, June 2013.
http://www.ietf.org/rfc/rfc6960.txt
[SARBANES]
Sarbanes-Oxley Act of 2002.
http://www.gpo.gov/fdsys/pkg/PLAW-107publ204/html/PLAW-107publ204.htm
[USEUSAFEHARB]
U.S.-EU Safe Harbor
http://export.gov/safeharbor/eu/eg_main_018365.asp
MQTT-3.1.1-CN 12
1.5 data representation
1.5.1 binary bit
the bits in the byte from 0 to 7. No. 7 bit is the highestsignificant bit, the 0 The bit is the least significant bit.
1.5.2 integer value
The integer value is 16 bits, using big-endian (big-endian,high-orderbytebefore the low-order bytefront). This meanswith a 16 bitscharacter in network
on the network represented as the highestsignificant byte (MSB), followed bythe least significant wordsection (LSB)。
1.5.3 UTF-8 Encoded string
the control described latertext in the control messagethis field is encoded as UTF-8 format charactersstring.UTF-8 [RFC3629] is aefficient
Unicode character encodingformat, to support radixfor textual communication, it is ASCII Characterthe encoding performsoptimized.
Each stringhas a two-bytelength field asas a prefix, it givesout this string UTF-8 encoded bytesnumber,theyInlegend
1.1 UTF-8 editstructure of a code string described indescribed. Therefore, what can be transmitted UTF-8 encodingthe string size has alimit, cannot exceedpass
65535 byte。
Unless otherwise specified,all UTF-8 editcode stringthe length must be 0 to 65535 bytewithin this range。
legend 1.1 UTF-8 encoded characterend of the stringstructure
binary bit
7
6
4
3
2
1
0
byte 1
the maximum string lengthhigh-order byte (MSB)
byte 2
the maximum string lengthlow-order byte (LSB)
byte 3 ….
if the length is greater than 0, here is UTF-8 the encoded character countdata.
UTF-8 encodingthe characters in the stringcharacter dataRequiredis according to Unicode Specification [Unicode] defined and in RFC3629 [RFC3629] Medium
reaffirmed valid UTF-8 format. It is particularly necessaryto point out that,TheseDatacannotcontains the character code at U+D800 and U+DFFF between
data.ifserver or client receivesarrived at a containingInvalid UTF-8 control of characterspacket, itRequiredclose networkconnection [MQTT-
1.5.3-1]。
UTF-8 encodingthe stringcannotcontains a null character U+0000。ifclient or server receivesarrived at a containing U+0000 of controlcontrol packet
text,itRequiredclose the network connection [MQTT-1.5.3-2]。
in the datashould notcontains the following Unicode code pointthe encoding. Ifa receiver (server or client) received a packetcontains the following
control of arbitrary characterspacket, itYesclose network connectionconnect:
U+0001 and U+001F betweenControl character
U+007F and U+009F betweenControl character
Unicode Specificationdefined non-character code point (e.g., U+0FFFF)
Unicode Specificationdefined guaranteereserved characters (e.g. U+0FFFF)
MQTT-3.1.1-CN 13
UTF-8 encodingsequence 0XEF 0xBB 0xBF alwaysis interpreted as U+FEFF(zero-width non-breaking spacecharacter),no matterit appears in the character
what position in the string,all message receiverscannot skip orstrip it [MQTT-1.5.3-3]。
1.5.3.1 non-normativeExample
For example, string A𪛔 Yesa LatinLetter A followed by acode point U+2A6D4(It represents aCJK Unifiedideographic character
Extensions B character in),Thisstring encodingas follows:
legend 1.2 UTF-8 encoded characternon-normative stringexample
Bit
7
6
5
4
3
2
1
0
byte 1
string length MSB (0x00)
0
0
0
0
0
0
0
0
byte 2
string length LSB (0x05)
0
0
0
0
0
1
0
1
byte 3
‘A’ (0x41)
0
1
0
0
0
0
0
1
byte 4
(0xF0)
1
1
1
1
0
0
0
0
byte 5
(0xAA)
1
0
1
0
1
0
1
0
byte 6
(0x9B)
1
0
0
1
1
0
1
1
byte 7
(0x94)
1
0
0
1
0
1
0
0
1.6 editorial conventions
This specification uses yellow highlightingbright text identifierconformance statement,each conformance statementare each assigned one suchFormat reference:[MQTT-x.x.x-
y]。
MQTT-3.1.1-CN 14
2 MQTT control packetFormatting
2.1 MQTT Structure of control messages
MQTT protocol communicationthrough exchange predeterminedsemantic MQTT control packet toCommunication. This sectiondescribes these packetsformat.
MQTT control packetpacket consists of three partscomposed, according to legend 2.1 –MQTT controlcontrol packet structure order of description:
legend 2.1 –MQTT control packet'sStructure
Fixed header solidfixed header, allcontrol packets all includecontain
Variable header variable header,some control packetscontains
Payload payload, some control packetscontains
2.2 fixed header
each MQTT controlcontrol packets all containa fixed header。legend 2.2 -solidformat of the fixed header describes the fixed headerformat of the header.
legend 2.2 -Fixedheader formatformula
Bit
7
6
5
4
3
2
1
0
byte 1
MQTT control packetmessage type
used forof the specified control message typeflag bit
byte 2…
remaininglength
2.2.1 MQTT Types of control messages
position:No. 1 a byte, binary bits 7-4。
represented as 4 no bitsymbol values, these valuessee definition Table 2.1 -Types of control messages
Table 2.1 -controlpacket typetype
name
Value
messageflow direction
Description
Reserved
0
Deny
retain
CONNECT
1
client to server
Client requests connectionServer-side
CONNACK
2
server to client
connect packetacknowledgment
PUBLISH
3
both directions are allowed
publish message
PUBACK
4
both directions are allowed
QoS 1 Messagepublishreceivedacknowledgment
PUBREC
5
both directions are allowed
Publish received (guaranteeddelivery step 1)
PUBREL
6
both directions are allowed
Publish release (guaranteeddelivery step 2)
MQTT-3.1.1-CN 15
PUBCOMP
7
both directions are allowed
QoS 2 MessagePublish Complete (guaranteeguaranteed interaction step 3)
SUBSCRIBE
8
client to server
Client subscription request
SUBACK
9
server to client
subscription requestmessageacknowledgment
UNSUBSCRIBE
10
client to server
Client unsubscribesrequest
UNSUBACK
11
server to client
Cancel subscriptionmessageacknowledgment
PINGREQ
12
client to server
heartbeat request
PINGRESP
13
server to client
heartbeat response
DISCONNECT
14
client to server
Client disconnects
Reserved
15
Deny
retain
2.2.2 Flags
fixed header, the 1 the remaining bytes 4 bits [3-0]contains each MQTT control packetmessage-type-specific flags,see Table 2.2 -flag bit。
Table 2.2 any marked as“retain”flag bits, all are reservedfor future use,Requiredset as in the tablelisted values [MQTT-
2.2.2-1]。ifupon receiving an invalid flag, the receiverreceiverRequiredClose the network connection. There arerelated to error handlingFor details, see 4.8 section [MQTT-
2.2.2-2]。
Table 2.2 -flag bit
control packet
solidfixed header flags
Bit 3
Bit 2
Bit 1
Bit 0
CONNECT
Reserved
0
0
0
0
CONNACK
Reserved
0
0
0
0
PUBLISH
Used in MQTT 3.1.1
DUP
1
QoS
2
QoS
2
RETAIN
3
PUBACK
Reserved
0
0
0
0
PUBREC
Reserved
0
0
0
0
PUBREL
Reserved
0
0
1
0
PUBCOMP
Reserved
0
0
0
0
SUBSCRIBE
Reserved
0
0
1
0
SUBACK
Reserved
0
0
0
0
UNSUBSCRIBE
Reserved
0
0
1
0
UNSUBACK
Reserved
0
0
0
0
PINGREQ
Reserved
0
0
0
0
PINGRESP
Reserved
0
0
0
0
DISCONNECT
Reserved
0
0
0
0
MQTT-3.1.1-CN 16
DUP
1
=controlduplicate delivery of packetssend flag
QoS
2
= PUBLISH messageofQuality of Service level
RETAIN
3
= PUBLISH of the packetretainFlags
PUBLISH controlin the packet DUP, QoS and RETAIN flag descriptiondescribed in 3.3.1 section.
2.2.3 remaining length
position:from the first 2 starts with a byte.
remaininglongdegree(Remaining Length)RepresentsWhenprevious messageremaining textremainderDivideofbytenumber,includingcanvariable messageheader andnegativeloadofData。remaininglongdegree
excluding the bytes used for encodingRemaining Length fieldits own byte count。
remaining lengthlength fielduse avariable lengthencoding methodcase,For less than 128 value ofit makesUse single charactersectionencoding. largervalue as belowway ofHandle.
Low 7 The significant bits are used to encode data., the most significant bitused to indicate whether there is morebytes of. Therefore each wordsection can encode 128 numberValue
and a
continuation bit (
continuation bit
)
. The Remaining Length fieldmaximum 4 characterssection.
non-normativecommentary
ExampleFor example,tenentersystemnumber 64 willByeditcodeisoneitemsCharactersection, valueYes 64,tensixentersystemTableshowis 0x40,。tenentersystemnumberCharacter
321(=65+2*128)is encodedis two bytes,the least significant bit is atbefore. The first wordsection is 65+128=193. note that the mosthigh bit is
1 Representsbehindat leastthere is one more byte. The secondbytes are 2。
notSpecificationcommentary
这allowpermit shouldusesendmaximum 256MB(268,435,455)bigsmall ofcontrolsystem reporttext。 这itemsnumber ValueIn reporttextMediumofTable showYes:
0xFF,0xFF,0xFF,0x7F。
Table 2.4 of the Remaining Length fieldSizeshows the remaining length fieldthe value represented varies withbyte growth.
Table 2.4 remaining lengthof the fieldSize
byte count
minimum value
maximum value
1
0 (0x00)
127 (0x7F)
2
128 (0x80, 0x01)
16 383 (0xFF, 0x7F)
3
16 384 (0x80, 0x80, 0x01)
2 097 151 (0xFF, 0xFF, 0x7F)
4
2 097 152 (0x80, 0x80, 0x80, 0x01)
268 435 455 (0xFF, 0xFF, 0xFF, 0x7F)
respectively denote (eachlow-order of the byte 7 bitsused to encode data, the most significant bit is a flag bit):
1 when bytes,from 0(0x00)to 127(0x7f)
2 when bytes,from 128(0x80,0x01)to 16383(0Xff,0x7f)
3 when bytes,from 16384(0x80,0x80,0x01)to 2097151(0xFF,0xFF,0x7F)
4 when bytes,from 2097152(0x80,0x80,0x80,0x01)to 268435455(0xFF,0xFF,0xFF,0x7F)
MQTT-3.1.1-CN 17
non-normativecommentary
non-negative integer X uses a variable-length encoding schemethe algorithm is as follows:
do
encodedByte = X MOD 128
X = X DIV 128
// if there are more data to encode, set the top bit of this byte
if ( X > 0 )
encodedByte = encodedByte OR 128
endif
'output' encodedByte
while ( X > 0 )
MOD is a modeloperation,DIV is integer division,OR is a bitwise operation or(C languagein which are respectively%,/,|)
non-normativecommentary
of the Remaining Length fieldthe decoding algorithm is as follows:
multiplier = 1
value = 0
do
encodedByte = 'next byte from stream'
value += (encodedByte AND 127) * multiplier
multiplier *= 128
if (multiplier > 128*128*128)
throw Error(Malformed Remaining Length)
while ((encodedByte AND 128) != 0)
AND is bit operationoperation AND (C in the language&)
when this algorithm terminates,value Packagewhat is included isthe value of the Remaining Length.
2.3 variable header
some MQTT control packetcontains a Variable Headerpart.it is in the fixed headerand payloadbetween. The Variable Headercontent according topacket type's
varies. Canvariable header packetidentifier (Packet Identifier)field exists inin messages of multiple types.
2.3.1 packet identifier
legend 2.3 -messageidentifier classtype
Bit
7
6
5
4
3
2
1
0
byte 1
packet identifier MSB
byte 2
packet identifier LSB
MQTT-3.1.1-CN 18
of many control packetsvariable header partcontains a two-byte messagepacket identifier field. Thesepacket is PUBLISH(QoS>0 time),
PUBACK,PUBREC,PUBREL,PUBCOMP,SUBSCRIBE, SUBACK,UNSUBSCIBE,
UNSUBACK。
SUBSCRIBE,UNSUBSCRIBE and PUBLISH(QoS greater than 0) control packetRequiredcontains aa non-zero 16 packet identifier bit
character (Packet Identifier)[MQTT-2.3.1-1]. The client each timesend a newof these types ofwhenever a messageRequiredassign acurrent
unused packet identifieridentifier [MQTT-2.3.1-2]. IfA client wants to resendthis special controlcontrol message, in later retransmissionthat message
when,itRequireduses the same identifier.When the client finishes processing thisa packet corresponding toAfter confirmation, thismessage identifier will bereleased as reusable.
QoS 1 of PUBLISH correspondingis PUBACK,QoS 2 of PUBLISH correspondingis PUBCOMP, and SUBSCRIBE or
UNSUBSCRIBE correspondingseparatelyYes SUBACK or UNSUBACK [MQTT-2.3.1-3]。send aitems QoS 0 of PUBLISH
messageWhen, the same conditions also apply toServer-side [MQTT-2.3.1-4]。
QoS Set to 0 of PUBLISH messagecannotcontains a packet identifier [MQTT-2.3.1-5]。
PUBACK, PUBREC, PUBREL messageRequiredcontaining andinitially sent PUBLISH reportpacket with the samemessage identifier [MQTT-2.3.1-
6]. Similarly,SUBACK and UNSUBACK Requiredcontained in the corresponding SUBSCRIBE and UNSUBSCRIBE reportused in the textof
packet identifier [MQTT-2.3.1-7]。
requiresThe control packet of the message identifier is in Table 2.5 -contains a packet identifiercontrol packet of listed in.
Table 2.5 -containsmessage identifiersymbol's controlcontrol packet
control packet
packet identifieridentifier charactersegment
CONNECT
Not Required
CONNACK
Not Required
PUBLISH
required (if QoS > 0)
PUBACK
requires
PUBREC
requires
PUBREL
requires
PUBCOMP
requires
SUBSCRIBE
requires
SUBACK
requires
UNSUBSCRIBE
requires
UNSUBACK
requires
PINGREQ
Not Required
PINGRESP
Not Required
DISCONNECT
Not Required
MQTT-3.1.1-CN 19
client and serverindependently assignedmessage identifiers. Therefore, the clientserver-side combinationusing the same messagemessage identifier can be implemented and
the sent message exchange.
non-normativecommentary
The client sends an identifiercharacter is 0x1234 of PUBLISH packet,it cancan be when receiving thatof a message PUBACK ofbefore, first
receives sent by the serveranother differentbut the message identifieridentifier is also 0x1234 of PUBLISH packet.
Client Server
PUBLISH Packet Identifier=0x1234---
--PUBLISH Packet Identifier=0x1234
PUBACK Packet Identifier=0x1234---
--PUBACK Packet Identifier=0x1234
2.4 payload
some MQTT control packet in the packetthe last part of the packetcontains a validpayload, this will be in thediscussed in Chapter 3.for PUBLISH speakingvalid
payloadis the application message.Table 2.6 – contains validcontrol packet with a payload lists the requirementsControl packet of the payload.
Table 2.6 – contains the payloadcontrol messagetext
control packet
payload
CONNECT
requires
CONNACK
Not Required
PUBLISH
Optional
PUBACK
Not Required
PUBREC
Not Required
PUBREL
Not Required
PUBCOMP
Not Required
SUBSCRIBE
requires
SUBACK
requires
UNSUBSCRIBE
requires
UNSUBACK
Not Required
PINGREQ
Not Required
PINGRESP
Not Required
DISCONNECT
Not Required
MQTT-3.1.1-CN 20
3 MQTT control packet
3.1 CONNECT – connectionServer-side
client to servernetwork connection establishmentafter establishment, the client sends toServer-sidethe first message ofRequiredYes CONNECT message [MQTT-
3.1.0-1]。
on a network connectionon, the client onlycan be sent once CONNECT message. ServerRequiredthe client sendsthe second sent CONNECT
packet as a protocol violationhandle normally and disconnectclient's connection [MQTT-3.1.0-2]. Regarding errorsFor the processed information, please refer to 4.8 section.
the payload contains aone or more encodingsfields. Includingclient's uniqueidentifier,Will topic,Will message, useusername and password.divide
the client identifieroutside,otherThe fields are all optional, based on the flag bitsto determine the variable messagein the headerwhetherThese fields need to be included。
3.1.1 fixed header
legend 3.1 –CONNECT the message's fixedfixed header
Bit
7
6
5
4
3
2
1
0
byte 1
MQTT packet typetype (1)
Reserved retainbits
0
0
0
1
0
0
0
0
byte 2…
remaining length value
remaining lengthlength field
the Remaining Length equals the Variable Headerlength of the variable header(10 byte) plus the payloadthe length. Encodingsee method 2.2.3 sectiondescription.
3.1.2 variable header
CONNECT reportVariable header of the messageThe header contains in the following orderfour fields: protocolname (Protocol Name), protocolLevel(Protocol
Level),connectionflag (Connect Flags) andKeep Alive (Keep Alive)。
3.1.2.1 Protocolname
legend 3.2 -Protocolnamecomposed of bytes
Description
7
6
5
4
3
2
1
0
protocol name
byte 1
length MSB (0)
0
0
0
0
0
0
0
0
byte 2
length LSB (4)
0
0
0
0
0
1
0
0
byte 3
‘M’
0
1
0
0
1
1
0
1
byte 4
‘Q’
0
1
0
1
0
0
0
1
byte 5
‘T’
0
1
0
1
0
1
0
0
MQTT-3.1.1-CN 21
byte 6
‘T’
0
1
0
1
0
1
0
0
The Protocol Name is a string that represents the protocolprotocol name MQTT of UTF-8 the encoded string.MQTT of the specificationLater versions will notchange thisstring offsetand
length.
if the protocol name is incorrectconfirm the serverYesdisconnect the clientthe connection, alsoYesaccording tosome other specificationscontinue processing CONNECT message. For
in the latter case,in accordance with this specification,Server-sidecannotcontinue processing CONNECT message [MQTT-3.1.2-1]。
notSpecificationcommentary
packet inspection tool, for example firewalls, can use the protocolprotocol name to identify MQTT traffic.
3.1.2.2 protocol levelother
legend 3.3 - Protocol Level byte ProtocolLevelbyteconstitute
Description
7
6
5
4
3
2
1
0
protocol level
byte 7
Level(4)
0
0
0
0
0
1
0
0
client uses 8 bit's unsignedsymbol value indicatesprotocol revision. Forin 3.1.1 editionprotocol, protocol levelvalue of the identifier fieldYes 4(0x04). If sending
detect an unsupported protocollevel, the serverRequiredsend tosend a return codeis 0x01(notsupported protocol leveldifference) of CONNACK messageresponse
CONNECT message, then disconnectdisconnect the client'sconnection [MQTT-3.1.2-2]。
3.1.2.3 connection identifierwill
the Connect Flags byte containscontains some used to indicatedecide MQTT connectconnection behavior parameters. It also indicates that there arecharacters in the payloadwhether the field exists.
legend 3.4 -connect flag bits
Bit
7
6
5
4
3
2
1
0
User Name
Flag
Password
Flag
Will Retain
Will QoS
Will Flag
Clean
Session
Reserved
byte 8
X
X
X
X
X
X
X
0
Server-sideRequiredverify CONNECT control packetthe text's retain flagbit (the 0 bits) whether it is 0,ifis not 0 must disconnectclient connection
[MQTT-3.1.2-3]。
3.1.2.4 clean sessionspeech
position:The bit of the connect flags byte 1 bits
this bit indicatesdetermines the session statethe processing method.
client and servercan save the sessionstate, to supportacross a network connectionreliable message transmission. This flag bitused to control session state
time to live.
MQTT-3.1.1-CN 22
If the Clean Session (CleanSession)flag is setset to 0, the serverRequiredbased oncurrent session (makeIdentified by the client identifierdifference) of
state restoration and the clientcommunication between the ends. Ifif there is no with thisclient identifierassociated session,Server-sideRequiredcreate aa new session. In
after the connection is closed,after the connection is disconnected, client and serverserverRequiredpreserve session informationbreath [MQTT-3.1.2-4]. When cleaningsession flag is 0
The session connection is disconnected.afterwards, the serverRequireditafter QoS 1 and QoS 2 Levelthe message is saved asof the session statea part, if这
Some messages match the disconnection.when connecting, the clientany subscriptions [MQTT-3.1.2-5]。the server alsoYesSavesatisfies the same conditionof QoS 0 Level
message.
ifclearmanageSession(CleanSession)markwillBySettingsis 1,clientendandServicesendRequireddiscardofbeforedutyhow cansession andopenstartaNew
ofwillspeech。willspeechonlyholdcontinueandnetnetworkconnectJiesamesamplelongofwhenbetween。and这itemswillspeechcloseuniteofstateconditionnumberaccording tocannotBydutywhatofafterofwillspeechheavyuse
[MQTT-3.1.2-6]。
The client's session state.state includes:
Has been sent to the server.end,ButNot yet acknowledged QoS 1 and QoS 2 levelother messages
Has been received from the server., but has not yetof the completion acknowledgment QoS 2 levelother messages.
The server's session state.state includes:
SessionWhether it exists, even if the session stateall the other partsis empty.
The client's subscription information.message.
Has been sent to the client.end,ButNot yet acknowledged QoS 1 and QoS 2 levelother messages。
about toTransmitted to the client. QoS 1 and QoS 2 levelother messages。
Has been received from the client., but has not yetof the completion acknowledgment QoS 2 levelother messages.
optional,prepareSent to the client. QoS 0 messages of the level。
Retained messages are not server-side.server session statea part of, willwhen the session terminatescannotdelete retained messagesbreath [MQTT-3.1.2.7]。
Regarding state storage.limitations and details seeNo. 4.1 section.
When the clean session flagis set to 1 when,client and serverserver-side state deletion does not needif atomic operation。
non-normativecommentary
To ensure that in the event ofstate on failureconsistency, the clientend should use sessionsession state flag 1 heavyrepeated connection request, until the connection succeeds
success.
non-normativecommentary
Generally speaking, clientsthe end always when connectingwill clean the session flagflag is set to 0 or 1,And do not alternately use the twokind of value. Thisselect take
Depends on the specific application.. Clean session flagflag is set to 1 the client does notwill receive oldapplication message,moreoveron each connectionafter success
All need to resubscribe.anyrelatedTopic. Clean sessionflag is set to 0 ofThe client will receive allwhen it connectsdisconnectduring sending
published QoS 1 and QoS 2 message at the level. Therefore,must ensurenot lost while the connection is disconnectedthe message, needUsage QoS 1 or
QoS 2 Level, simultaneously will cleanThe session flag is set to 0。
non-normativecommentary
MQTT-3.1.1-CN 23
clean session flag 0 When the client connectsIt requests the server toafter the connection is disconnected, saveretain its MQTT session state.if open
Planned at some laterreconnect at the time point tothis server,the client connection shouldshould only use cleansession flag 0. When the client decides
afterWhen no longer using this session, shouldshould clean the sessionflag is set to 0 finally thenconnect once,Then disconnect.
3.1.2.5 will flag
position:The connect flags' 2 bit.
willflag (Will Flag) is setis 1, indicating ifIf the connection request isaccepted, the will(Will Message)MessageRequiredis stored in
The server and with thisa network connection associatedassociated. After the networkwhen the connection is closed,Server-sideRequiredpublish thiswillmessage,unlessserver receives
DISCONNECT when the message is deletedThiswillMessage [MQTT-3.1.2-8] 。
The will message publishedconditions, including butnot limited to:
The server has detecteda I/O Error or network failure。
The client is maintaining the connectionconnection (Keep Alive)within the time period failed tocommunication.
The client did not send firstsend DISCONNECT The message directly closed the network connection.
Due to a protocol error, the serverthe server closed the networknetwork connection.
ifThe will flag is set to 1, connectionin the connection flag Will QoS and Will Retain Fieldswill be used by the serverto,at the same timein the payloadmust
needcontains Will Topic and Will Message Fields [MQTT-3.1.2-9]。
Once published orthe server receivedsent by the client DISCONNECT packet,willmessage thenRequiredRemoved from stored session state.
divide [MQTT-3.1.2-10]。
ifThe will flag is set to 0,connectionin the flag Will QoS and Will Retain FieldsRequiredSet to 0, andin the payloadcannot
contains Will Topic and Will Message Fields [MQTT-3.1.2-11]。
ifThe will flag is set to 0, networkwhen the network connection is disconnected,cannotsend the will message [MQTT-3.1.2-12]。
the server shouldrapidlyemitclothwillMessage。Inclosemachineorfaultoffeelingunder circumstances,the server maypostponewilleliminateinformationemitclothstraighttoafterofheavystart.
If this kind ofcase, at the serverserver failure and willafter the message is publishedthere may be a delay between。
3.1.2.6 will QoS
position:The connect flags' 4 and the 3 bit.
These two bits are used to specifypublishwillThe service used when sending a messagequality level.
ifThe will flag is set to 0,will QoS alsoRequiredSet to 0(0x00) [MQTT-3.1.2-13]。
ifThe will flag is set to 1,will QoS value ofcan equal 0(0x00),1(0x01),2(0x02). Itvalue ofcannotequals 3
[MQTT-3.1.2-14]。
3.1.2.7 will retain
position:The connect flags' 5 bit.
MQTT-3.1.1-CN 24
ifWhen the will message is published, it needs to be preservedretain, need to specifythe value of this bit.
ifThe will flag is set to 0, leavewill retain (Will Retain)flag alsoRequiredSet to 0 [MQTT-3.1.2-15]。
ifThe will flag is set to 1:
ifThe will retain is set to 0, the serverRequiredTreat the will message as non-retained message publishing [MQTT-3.1.2-16]。
ifThe will retain is set to 1, the serverRequiredtreat the will message asPublished as a retained message [MQTT-3.1.2-17]。
3.1.2.8 UsernameFlags
position:The connect flags' 7 bit.
if the username (User Name) flag is set to 0, in the payloadcannotcontainsusername field [MQTT-3.1.2-18]。
if the username (User Name) flag is set to 1, in the payloadRequiredcontainsusername field [MQTT-3.1.2-19]。
3.1.2.9 password flagwill
position:The connect flags' 6 bit.
if the password (Password) flagis set to 0, in the payloadcannotcontains a password field [MQTT-3.1.2-20]。
if the password (Password) flagis set to 1, in the payloadRequiredcontains a password field [MQTT-3.1.2-21]。
If the username flagis set to 0, the password flag alsoRequiredSet to 0 [MQTT-3.1.2-22]。
3.1.2.10 keep alive
legend 3.5 keep alivebyte
Bit
7
6
5
4
3
2
1
0
byte 9
keep alive Keep Alive MSB
byte 10
keep alive Keep Alive LSB
Keep Alive (Keep Alive) is aa value in secondsthe time interval, expressed asa 16 The word of bits, which refers tothe client finishes transmittingCheng
from the moment of one control message to the moment of sending the next message, bothbetweenallowpermitEmptyidlethe mostbigwhenintervalseparate。client is responsibleprotectprovecontrol
messageemitsendofwhenintervalseparateNoexceedpassThe keepalive value.ifnotYesanyitsitof controlsystemreporttext canwithemitsend,clientRequiredsenda
PINGREQ message [MQTT-3.1.2-23]。
regardlessWhat is the keep alive value, clientclient at any timecan all be sent PINGREQ Packet, and use PINGRESP message to determine network
Network and server-side activityactive state.
if the keepalivevalue ofnotzero, andandclothesserverInonepoint fivetimesofprotectmaintain connectionJiewhenbetweeninsidenoreceivetoclientendofcontrolreporttext,itRequiredbreak
Open the client's networkconnection, consider the networknetwork connection has been disconnected [MQTT-3.1.2-24]。
the client has sent PINGREQ messageAfterwards, if within a reasonable period of timestill has not received PINGRESP packet, itshouldclose to the server
The endpoint's network connection.
MQTT-3.1.1-CN 25
The value of the keep-alive iszero indicatesshowclose keepholdconnectJiemeritability。this means, serviceendNoNeedwantbecauseguesthouseholdendpoint notactiveandbreakopenconnectconnect.Note:
Regardless of the value of the keep-alive, at any time, as long asclothesaffairendpoint recognizesisThe client is inactive or unresponsive and can be disconnected.clientendpoint'sconnect
connect.
non-normativecommentary
The actual keep-alive valuevalue is specified by the applicationspecified, usuallya few minutes. Allowthe maximum value is 18 hours 12 Divide 15 seconds.
3.1.2.11 variable header non-normativescopeExample
legend 3.6 -variable headernon-normativeExample
Description
7
6
5
4
3
2
1
0
protocol name
byte 1
Length MSB (0)
0
0
0
0
0
0
0
0
byte 2
Length LSB (4)
0
0
0
0
0
1
0
0
byte 3
‘M’
0
1
0
0
1
1
0
1
byte 4
‘Q’
0
1
0
1
0
0
0
1
byte 5
‘T’
0
1
0
1
0
1
0
0
byte 6
‘T’
0
1
0
1
0
1
0
0
protocol level
Description
7
6
5
4
3
2
1
0
byte 7
Level (4) Level
0
0
0
0
0
1
0
0
connection flag Connect Flags
byte 8
User Name Flag (1) username flag
Password Flag (1) densecode flag
Will Retain (0) Will retain flag
Will QoS (01) Will Quality of Service
Will Flag (1) Will Flags
Clean Session (1) cleanupSession
Reserved (0) reserved bit
1
1
0
0
1
1
1
0
keepalive time
byte 9
keep alive MSB (0)
0
0
0
0
0
0
0
0
byte 10
keep alive LSB (10)
0
0
0
0
1
0
1
0
MQTT-3.1.1-CN 26
3.1.3 payload
CONNECT reportthe payload of the messagepayload (payload) contains one ormultiple length-encodeda field prefixed with, the flags in the variable headerdeterminewhether
Contains these fields.if included,RequiredAppear in this order: client identifieridentifier, the will topicissue,willMessage, username, password
code [MQTT-3.1.3-1]。
3.1.3.1 clientIdentifiers
clothesaffairendmakeuseguesthouseholdendmarkknowsymbol (ClientId) knowotherguesthouseholdend。connectJieclothesaffairendofeveryitemsguesthouseholdendallYesonlyoneofguesthouseholdendmarkknowsymbol
(ClientId)。client and serverthe endpoints must use ClientId knowdistinguish between the twobetween MQTT Session-related statecondition [MQTT-3.1.3-
2]。
client identifier (ClientId) RequiredExistsmoreoverRequiredYes CONNECT messageThe payload's firsta field [MQTT-3.1.3-3]。
client identifierRequiredYes 1.5.3 defined in the section UTF-8 Encoded string [MQTT-3.1.3-4]。
Server-sideRequiredAllowed 1 to 23 bytes long UTF-8 encoded clientClient identifier, the clientthe client identifier can only containthese characters:
“0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”(uppercase letters,Lowercase letters
and numbers)[MQTT-3.1.3-5]。
Server-sideYesallows the encoded ... to exceedpass 23 charactersclient of the sectionIdentifiers (ClientId). ServerYesallow packetscontaining those not listed aboverepresent character
The client identifier (ClientId)。
Server-sideYesallows the client to provideprovide a zero characterThe client identifier of the section (ClientId) , ifHaving done this,Server-sideRequiredTreat this as a special
Special cases and assign uniqueunique client identifieridentifier to that clientclient. Then itRequiredSupposethe client providedThat unique clientidentifier
character,normal processingThis CONNECT message [MQTT-3.1.3-6]。
If the client providesa zero-byteof the client identifiersymbol, itRequiredwill also clearsession flag setset to 1 [MQTT-3.1.3-7]。
If the client providesof ClientId is zero bytesand the Clean Session flagmarked as 0, serviceendRequiredsends a return code of 0x02(Indicating the identifier is not
valid) of CONNACK packet responserespond to the clientof CONNECT message,thenclose the network connection [MQTT-3.1.3-8]。
If the server rejectsof this ClientId,itRequiredsendreturn code is 0x02(tableindicates that the identifier is invalidformat) of CONNACK packet response
client's CONNECT packet,then closes the networkconnection [MQTT-3.1.3-9]。
non-normativecommentary
The client implementation mayprovides a convenientmethod used to generate randomof ClientId. When the Clean Sessionflag is set to 0 shouldthat
Proactively abandon the use of thisa method.
3.1.3.2 will topic
ifThe will flag is set to 1, there isthe next field of the payloadfield is the Willtopic (Will Topic). WilltopicRequiredYes 1.5.3 section specifies
semantic UTF-8 encodingString [MQTT-3.1.3-10]。
MQTT-3.1.1-CN 27
3.1.3.3 will message
ifThe will flag is set to 1, there isthe next field of the payloadfield is the Willmessage. The Will messagemessage defines what will bepublished to the Will topictopic's response
Use the message, see 3.1.2.5 description of the section. This field consists ofa two-bytelength and the Will messagethe message's payloadcomposed of, represented aszero bytes or
Multiple byte sequences.length gives the followingdata that followsnumber of bytes, notcontainslengthThe two bytes occupied by the field itselfbytes.
willWhen a message is published to the will topic, its payloadpayload contains only thisfield dataPart, does not include the openingthe two length fields of the headerbyte.
3.1.3.4 Username
if the username (User Name) flag is set to 1, the next part of the payloadfields are exactly it.UsernameRequiredYes 1.5.3 sectiondefined
UTF-8 encodingString [MQTT-3.1.3-11]. serviceserver canit is used for identityauthentication and authorization.
3.1.3.5 Password
if the password (Password) flagis set to 1, the next field of the payload isit. passwordthe code field contains a two-bytelength of the section
Fields,lengthIndicates the number of bytes of binary data(not including the length field itselfthe two bytes occupied by itselfbytes), thenfollows 0 to 65535 byte
The binary data.
legend 3.7 - password bytes
Bit
7
6
4
3
2
1
0
byte 1
data length MSB
byte 2
data length LSB
byte 3 ….
if the length is greater than 0, here is the data portion
3.1.4 response
Note: The server mayso that in the same TCP port or itsSupport on other network endpointssupports multiple protocols (including thisearly version of the protocolthis).if the server
The server determines the protocol is MQTT 3.1.1, thenit follows the followingMethod for verifying connectionrequest.
1. After the network connection is established, if the serverwithin a reasonable timedid not receive within CONNECT reportpacket, the servershouldClosethis connection
connect.
2. Server-sideRequiredaccording to 3.1 section requirement verification CONNECT packet,ifpacket does not conform tospecification, the serverdoes not send
CONNACK messageclose directlyNetwork Connection [MQTT-3.1.4-1]。
3. Server-sideYesChecks CONNECT of the packetwhether the content satisfiessatisfy any furtherrestriction,Yesperform identityauthentication and authorization
Checks. If any check does not passhowever, according to 3.2 the section's description, itshouldsend an appropriateappropriate,non-zero return code
CONNACK response, andRequiredclose this network connection.
If verification succeeds,the server will executethe following steps.
1. if ClientId indicatesThe client has connected to this serverServer, then the serverRequireddisconnect the existing clientclient connection [MQTT-
3.1.4-2]。
2. Server-sideRequiredaccording to 3.1.2.4 sectionofDescriptionExecuteThe session cleanup process [MQTT-3.1.4-3]。
3. Server-sideRequiredsends a return code ofzero's CONNACK packet as CONNECT of the packetacknowledgment response [MQTT-3.1.4-4]。
4. Start message distribution andmaintain the connection statemonitor.
MQTT-3.1.1-CN 28
Allowedthe client is sending CONNECT messageimmediately sends afterwardsOther control packets;client does notNeed to wait for the server's CONNACK
packet.ifthe server rejected CONNECT, itcannotprocess the clientIn CONNECT after the packet, sendany data sent [MQTT-
3.1.4-5]。
non-normativecommentary
The client usually waitswait for a CONNACK packet. However,the client has the right toreceived CONNACK beforesend control packets,
Since there is no need to maintainconnection state, thiscan simplify the implementation of the clientappear.
3.2 CONNACK – acknowledge connection requestFind
the server sends CONNACK messageresponse from the clientreceived CONNECT reportpacket. The serversent to the clientthe first message ofmust
needYes CONNACK [MQTT-3.2.0-1]。
If the client is inwithin a reasonable time did notreceived from the serverof CONNACK packet,clientshouldClose networknetwork connection.
reasonable
the time taken
Depends on the type of applicationand communication infrastructureimplement.
3.2.1 fixed header
The fixed header formatsee legend 3.8 – CONNACK reporttext fixedfixed header the description of。
legend 3.8 – CONNACK packet fixed header
Bit
7
6
5
4
3
2
1
0
byte 1
MQTT control packet type (2)
Reserved reserved bit
0
0
1
0
0
0
0
0
byte 2
remaining length (2)
0
0
0
0
0
0
1
0
remaining lengthlength field
RepresentsThe length of the Variable Header. For CONNACK messagethis value equals 2。
3.2.2 variable header
The variable header formatsee legend 3.9 –CONNACK Message canvariable header ofdescription.
legend 3.9 –CONNACK packet variable header
Description
7
6
5
4
3
2
1
0
connection acknowledgement flags
Reserved reserved bit
SP
1
byte 1
0
0
0
0
0
0
0
X
connection return code
byte 2
X
X
X
X
X
X
X
X
MQTT-3.1.1-CN 29
3.2.2.1 Connection acknowledgmentAcknowledgment flag
No. 1 bytes are
connection acknowledgement flags
, bit 7-1 is to ensureReserved bit andRequiredSet to 0。
No. 0 (SP)bits is currentSession(Session Present)Flags。
3.2.2.2 current sessionspeech
position:The bit of the connection acknowledgment flag 0 bit.
If the server receivesClean Session (CleanSession)Flagsis 1 ofconnection, exceptwould CONNACK The return code in the packetSet to 0
in addition, alsoRequiredwill CONNACK in the packetcurrent session setting(Session Present)Flagsis 0 [MQTT-3.2.2-1]。
If the server receivesa CleanSession is 0 ofconnection,current session flagthe value depends on whether the server iswhether it has already saved ClientId
The corresponding client's sessionsession state. Ifthe server has already savedstored the session state, itRequiredwill CONNACK The current session in the packetsession flag set
set to 1 [MQTT-3.2.2-2]。If the serverthere is no savedsession state, itRequiredwill CONNACK reportin the messagecurrent session setting
is 0. It is also necessary to CONNACK reportthe return code in the text is set to 0 [MQTT-3.2.2-3]。
The current session flag is usedserver and clientwhether there is alreadypreserve on the stored session stateremain consistent.
onceCompleted the session initialization settings, already saved the sessionthe client with session state will expectexpects the server to maintainit storesthe session state.if client
The client receives from the serverreceivedcurrentThe value differs from the expected, the client canChoose to continue thissession or disconnect.clientcan discard
Abandon the client and serversession between endpointsstate, methodis,disconnect, thenClean Session flagflag is set to 1, reconnect,thenagain
Disconnect.
If the server sendscontained a non-with a zero return code CONNACK packet, itRequiredwill serve asprevious session flagSet to 0 [MQTT-
3.2.2-4]。
3.2.2.3 connection returnresponse code
position:the Variable Header's 2 a byte。
Connect Return Code fieldusing a one-byteunsigned value,In Table 3.1 – connection returnvalue of the return code Listed in. If the server receivesa valid
method's CONNECT packet, but appearsfor some reason cannothandle it, the serverserver should trysend one containing a non-zero returnReturn code (in the tableof
of a particular one) CONNACK packet. Ifthe server sentone containing a non-zero return codeof CONNACK packet,then itRequiredclose
close network connection [MQTT-3.2.2-5].。
Table 3.1 –Value of the Connect Return Code
Value
return coderesponse
Description
0
0x00 connection acceptedaccept
The connection has been accepted by the serverAccept
1
0x01 connection refusedrefused, unsupportedprotocol version
The server does not support the clientrequested by the client MQTT protocol levelother
2
0x02 connection refusedrefused, nota valid client identifier
The client identifier iscorrect UTF-8 encoding,ButServices
endpoint is not allowed to use
3
0x03 connection refusedrefused, serverserver unavailable
The network connection has been established, but MQTT service unavailable
4
0x04 connection refusedrefused, invalidthe user name or password
of the user name or passwordinvalid data format
MQTT-3.1.1-CN 30
5
0x05 connection refusedrefused, notauthorization
The client is not authorizedconnect to this servicedevice
6-255
retain
If you think that in the above tableall connections returnnone of the return codes are suitable,thenServer-sideRequiredClose the network connection,do not need to send CONNACK report
text [MQTT-3.2.2-6]。
3.2.3 payload
CONNACK messageno validpayload.
3.3 PUBLISH – publish message
PUBLISH controlpacket refers to from clientclient to serveror the server to the clienttransmit an applicationmessage.
3.3.1 fixed header
legend 3.10 – PUBLISH reportpacket fixed headerdescribes the fixed headerheader format
legend 3.10 – PUBLISH packet fixed header
Bit
7
6
5
4
3
2
1
0
byte 1
MQTT control packetmessage type (3)
DUP
QoS level
RETAIN
0
0
1
1
X
X
X
X
byte 2
remaining length
3.3.1.1 retransmission flagwill
position:No. 1 byte, the 3 bits
if DUP flag is set to 0, indicating that this is a client or serverserver first requestrequest to send this PUBLISH packet.if DUP Flags
is set to 1, tableindicating this may be aan earlier packet requestretransmission of the request.
client or serverrequest to resend a PUBLISH when the message,Requiredwill DUP markflag is set to 1 [MQTT-3.3.1.-1].. For QoS
0 the message,DUP FlagsRequiredSet to 0 [MQTT-3.3.1-2]。
the server sends PUBLISH messageto the subscriberwhen,receivedof (inbound) PUBLISH of the packet DUP value of the flagwill not be propagated.emit
sent (outbound) PUBLISH messageand receivedof (inbound) PUBLISH in the packet DUP the flag is independentindependently set,its valueRequired
individually according to the sendingof (outbound) PUBLISH messagewhether it is a retransmissionsent to determine [MQTT-3.3.1-3]。
non-normativecommentary
the receiver receives a DUP flag is 1 ofControl Packet,cannot assume it seesone before this packeta duplicate of.
non-normativecommentary
What needs to be specifically pointed out isis,DUP marklog focuses on controlcontrol packet itself,with the application message it containsirrelevant. When using QoS 1
when,A client might receive a DUP flag is 0 of PUBLISH packet,Thispacket contains aOne it had previously received
a copy of the application message, but the one used isdifferent packet identifieridentifier. 2.3.1 section provides someregarding the packet identifiermore information.
MQTT-3.1.1-CN 31
3.3.1.2 service qualitylevel
position:No. 1 byte, the 2-1 bit.
This field indicates the application messagefor message distributionquality of service level guarantee.service qualityquality level in Table 3.2 -quality of service definition listed inout.
Table 3.2 -Quality of Servicedefinition
QoS Value
Bit 2
Bit 1
Description
0
0
0
at most once
1
0
1
at least once
2
1
0
deliver only once
-
1
1
reserved bit
PUBLISH messagecannotwill QoS placesome bits are set to 1。ifserver or clientclientreceived QoS All bits are 1 of PUBLISH
packet, itRequiredclose network connectionJie [MQTT-3.3.1-4]。
3.3.1.3 retain flagwill
position:No. 1 byte, the 0 bit.
If the client sends toserver's PUBLISH of the packetretain (RETAIN)flag is setis 1, the serverRequiredstore this application message
information anditofServicesqualitywaitlevel(QoS), in order toconvenientitYesBydistributeto not yetcomeofmaintitlematchassignedsubscribereader [MQTT-3.3.1-5]。a
NewSubscriptionbuildimmediately, foreachmatchoftopicname,ifstoreInrecentprotectremainingeliminatemessage,itRequiredis sentsend toThissubscribereader [MQTT-
3.3.1-6]. If the Serverthe client receives a retained message(RETAIN) flag is 1 of QoS 0 message,itRequireddiscardpreviously for that topictopic retain
of any message. Itshouldwilla new QoS 0 message as that topica new retained message on the topic, butat any timeYeschooses to discard it
— ifWhen this occurs, thattopic will have no retainedretained message [MQTT-3.3.1-7]。related to storage stateFor more information, see 4.1 section.
Server-sidesend PUBLISH message towhen the client, e.g.if the message is as a clienta newthe subscription result is sentsend, itRequiredthe Packet's Retain
Retain flag set to 1 [MQTT-3.3.1-8]. When a PUBLISH reporttext sentsent to the client because it matchesassign an already establishedwhen the subscription, the server
serverRequiredSet the retain flag to 0, regardless of itthe received messagein the messageretainWhat is the value of the flag [MQTT-3.3.1-9]。
retainflag is 1 and validthe payload is zero bytesof PUBLISH reportmessage will bethe server treats it as a normal messageprocessing, it will besend to the subscribed topic
matchingclientend。in addition,sameamaintopicBottomanypresentstoreofretaineliminatebreathRequiredBymovedivide,Therefore这itemstopicofafterofanysubscribereadall
will not receiveto aretained message [MQTT-3.3.1-10]。
treated as normal
It meansexistingthe Client receivesof the messageMediumthe Retain flag is notis set。
Server-sidecannotstore zero-byteretained message [MQTT-3.3.1-11]。
If the client sends toserver's PUBLISH of the packetRetain flag bit 0,Server-sidecannotstore this messagealsocannotremove or replace any
existing retained messages [MQTT-3.3.1-12]。
non-normativecommentary
not determined for the publisherperiodically send status messagesmessage, in this scenario,retained messages are veryuseful. New subscriptionsthe subscriber will receive the most recent statestate.
remaining lengthlength field
equalsThe length of the variable header plus the payloadthe length of the payload.
MQTT-3.1.1-CN 32
3.3.2 variable header
Variable header in ordercontainstopicName and packet identifier.
3.3.2.1 topic name
topic name (Topic Name) used foridentify the payloadwhere the data should be publishedan information channel。
topic nameRequiredYes PUBLISH reportvariable headerThe first field of the header.itRequiredYes 1.5.3 sectiondefined UTF-8 encoded string
[MQTT-3.3.2-1]。
PUBLISH messageTopic Name in thecannotcontains wildcardmatching character [MQTT-3.3.2-2]。
The server sends to the subscriberof the subscribing Client PUBLISH messagetopic nameRequiredmatchthe topic of the subscriptionfilter (according to 4.7 matching defined in the section
process)[MQTT-3.3.2-3]。
3.3.2.2 packet identifieridentifier
only when QoS waitlevel is 1 or 2 when, packet identifier(Packet Identifier) fieldcan only appear in PUBLISH in the packet.2.3.1
The section provides information about the packetupdate of the packet identifiermore information.
3.3.2.3 variable headernon-normative headerExample
legend 3.11 – PUBLISH reportPacket Variable HeaderNon-normative example illustrates Table 3.3 - PUBLISH reportnon-normative example briefly describe
described PUBLISH the variable header of the packetheader.
Table 3.3 - PUBLISH Non-normative example of the message
Field
Value
topic name
a/b
packet identifier
10
legend 3.11 – PUBLISH packet variable headerNon-normative example
Description
7
6
5
4
3
2
1
0
Topic Name topic name
byte 1
Length MSB (0)
0
0
0
0
0
0
0
0
byte 2
Length LSB (3)
0
0
0
0
0
0
1
1
byte 3
‘a’ (0x61)
0
1
1
0
0
0
0
1
byte 4
‘/’ (0x2F)
0
0
1
0
1
1
1
1
byte 5
‘b’ (0x62)
0
1
1
0
0
0
1
0
packet identifier
byte 6
packet identifier MSB (0)
0
0
0
0
0
0
0
0
byte 7
packet identifier LSB (10)
0
0
0
0
1
0
1
0
MQTT-3.1.1-CN 33
The topic name in the exampleis “a/b”,lengthequals 3, the packet identifier is “10”
3.3.3 payload
The payload will containthe published applicationmessage. The datacontent and format areapplication-specific.the length of the payloadis calculated as follows:with fixed
the remaining length in the headerthe value of the Length field minussubtract the length of the variable header.contains zeropayload lengthof PUBLISH reportthe packet is valid.
3.3.4 response
PUBLISH messagethe receiverRequiredaccording toAccording to PUBLISH in the packet QoS QoS level to send a response, see the table belowformat description [MQTT-
3.3.4-1]。
Table 3.4 – PUBLISH the expected Packetresponse
Quality of Service level
expected response
QoS 0
no response
QoS 1
PUBACK message
QoS 2
PUBREC message
3.3.5 action
the Client uses PUBLISH the packet sends an applicationmessage to the server, in order to distributeto other matching subscriptionsmatching clients.
the Server uses PUBLISH the packet sends an applicationmessage to eachSubscriptionmatchthe client.
The client uses band-passwildcard topic filterwhen the filter requests a subscription, the clientthe client's subscription canmay be repeated,ThereforePublished messages may match multiple
a filter. ForIn this case, the serverserverRequireddelivers the message toall subscriptions matchingassigned QoS waitthe highest-level client [MQTT-3.3.5-
1]. The Server'sthen according to the subscriptionof QoS level, the distribution of the messagea copy to eachmatching subscribers。
receive a PUBLISH reportwhen the message,the receiver's actionDepends on 4.3 sectiondescribed QoS waitlevel.
ifThe server implementation does not authorize a clientclient publishes PUBLISH packet,it has no way to notify thatClient. ItRequiredaccording to normalnormal
QoS rule sendsend a positiveAcknowledgment, orclose the network connection [MQTT-3.3.5-2]。
3.4 PUBACK –emitpublish acknowledgment
PUBACK messageis correct QoS 1 levelof PUBLISH reportresponse to the packet。
3.4.1 fixed header
legend 3.12 - PUBACK reporttext fixeddetermined messagehead
Bit
7
6
5
4
3
2
1
0
byte 1
MQTT control packetmessage type (4)
reserved bit
0
1
0
0
0
0
0
0
MQTT-3.1.1-CN 34
byte 2
remaining length(2)
0
0
0
0
0
0
1
0
remaining lengthlength field
indicating the variable header'slength. For PUBACK messagethis value equals 2.
3.4.2 variable header
contains those awaiting acknowledgment PUBLISH the message's packetPacket Identifier.
legend 3.13 – PUBACK packet variable header
Bit
7
6
5
4
3
2
1
0
byte 1
packet identifier MSB
byte 2
packet identifier LSB
3.4.3 payload
PUBACK messageno payload。
3.4.4 action
see the full description in 4.3.2 section.
3.5 PUBREC – publishreceived (QoS 2, Step 1)
PUBREC reportmessage is correct QoS level 2 of PUBLISH reportthe response to the message. It is QoS 2 QoS protocol exchangethe second message of the exchangetext.
3.5.1 fixed header
legend 3.14 – PUBREC fixed messageheader
Bit
7
6
5
4
3
2
1
0
byte 1
MQTT control packetmessage type e (5)
reserved bit
0
1
0
1
0
0
0
0
byte 2
remaining length (2)
0
0
0
0
0
0
1
0
remaining lengthlength field
indicating the variable header'slength. For PUBREC reportmessage'svalue equals 2。
3.5.2 variable header
the variable header contains etc.pending acknowledgment PUBLISH reportPacket's Packet Identifieridentifier.
MQTT-3.1.1-CN 35
legend 3.15 – PUBREC variable messageheader
Bit
7
6
5
4
3
2
1
0
byte 1
packet identifier MSB
byte 2
packet identifier LSB
3.5.3 payload
PUBREC reportthe message has no payload。
3.5.4 action
see the full description in 4.3.3 section.
3.6 PUBREL – publishrelease (QoS 2, Step 2)
PUBREL messageis correct PUBREC the message's response.It is QoS 2 waitof the protocol-level exchangethe third message.
3.6.1 fixed header
legend 3.16 – PUBREL packet fixed header
Bit
7
6
5
4
3
2
1
0
byte 1
MQTT control packetmessage type (6)
reserved bit
0
1
1
0
0
0
1
0
byte 2
remaining length (2)
0
0
0
0
0
0
1
0
PUBREL controlPacket Fixed Headerheader's first 3,2,1,0 bit is the Retain bit,Requiredis set to 0,0,1,0. ServiceendRequiredany other value
are all treated as illegaland close the networkconnection [MQTT-3.6.1-1]。
remaining lengthlength field
indicating the variable header'slength. For PUBREL reportPacket's value equalsin 2.
3.6.2 variable header
the variable header contains andwaiting for acknowledgment PUBREC messagethe same message identifieridentifier.
legend 3.17 – PUBREL packet variable header
Bit
7
6
5
4
3
2
1
0
byte 1
packet identifier MSB
byte 2
packet identifier LSB
MQTT-3.1.1-CN 36
3.6.3 payload
PUBREL messagehas no Payloadpayload.
3.6.4 action
see the full description in 4.3.3 section.
3.7 PUBCOMP – Publish complete (QoS 2, step 3)
PUBCOMP reportmessage is correct PUBREL reportresponse to the packet. It is QoS 2 levelthe protocol exchange'sfourth and lasta Packet.
3.7.1 fixed header
legend 3.18 – PUBCOMP message fixedfixed header
Bit
7
6
5
4
3
2
1
0
byte 1
MQTT control packetmessage type (7)
reserved bit
0
1
1
1
0
0
0
0
byte 2
remaining length (2)
0
0
0
0
0
0
1
0
remaining lengthlength field
indicating the variable header'slength. For PUBCOMP reportthis texta value equals 2。
3.7.2 variable header
the variable header contains andwaiting for acknowledgment PUBREL messagethe same Packetidentifier.
legend 3.19 – PUBCOMP Message canvariable header
Bit
7
6
5
4
3
2
1
0
byte 1
packet identifier MSB
byte 2
packet identifier LSB
3.7.3 payload
PUBCOMP reportmessage has nopayload.
3.7.4 action
see the full description in 4.3.3 section.
MQTT-3.1.1-CN 37
3.8 SUBSCRIBE - subscription topic
client to serversend SUBSCRIBE message used forcreate one or moresubscriptions. Eachthe subscription registers the clienta topic that the client cares aboutor multiple
topic. In order toforward the message tomatching those subscriptionsmatched topic, the serverserver sends PUBLISH reportPacket to the Client。SUBSCRIBE
the message also (for eachthe subscription) specifiesmaximum QoS waitlevel, the Serversend based on thisdeliver the application message to the client.
3.8.1 fixed header
legend 3.20 – SUBSCRIBE message fixedfixed header
Bit
7
6
5
4
3
2
1
0
byte 1
MQTT control packetmessage type (8)
reserved bit
1
0
0
0
0
0
1
0
byte 2
remaining length
SUBSCRIBE controlcontrol packet fixed headerof the 3,2,1,0 bitsis retainedbit,Requiredrespectively set to 0,0,1,0. ServerRequiredany other
any value is treated as notvalid and closeNetwork Connection [MQTT-3.8.1-1]。
remaining lengthlength field
equalsThe length of the variable header (2 byte) plus the payloadlength of the Payload.
3.8.2 variable header
the variable header contains the clientclient identifier.2.3.1 Provideabout the PacketMore information about identifiers.。
3.8.2.1 variable headernon-normative headerExample
legend 3.21 – packet identifierequals 10 of the Variable Header, a non-normative exampleExample shows the messagethe message identifier is set to 10 Variable Header when
header.
legend 3.21 – messageidentifieridentifier equals 10 can bevariable messageheader, non-normative exampleExample
Description
7
6
5
4
3
2
1
0
packet identifier
byte 1
packet identifier MSB (0)
0
0
0
0
0
0
0
0
byte 2
packet identifier LSB (10)
0
0
0
0
1
0
1
0
3.8.3 payload
SUBSCRIBE of the packetpayloadcontains a topictopic filter list,they represent the Clientthe topics the client wants to subscribe to。SUBSCRIBE
messageTopic filter in the payloadListRequiredYes 1.5.3 sectiondefined UTF-8 String [MQTT-3.8.3-1]. serviceservershouldSupported
contains a wildcard (4.7.1 section specifiesmeaning) of thetopic filter. Ifif the server chooses not to supportcontaining wildcardstopic filter,RequiredReject
any containing wildcardsthe filter's subscriptionrequest [MQTT-3.8.3-2]。After every filterfollowed by a byte, this byte iscalled clothes
quality of service requirement (Requested QoS). It gives the serverServer to Clientthe client sends application messageallowed by the messagemaximum QoS level.
MQTT-3.1.1-CN 38
SUBSCRIBE of the packetpayloadRequiredcontainsat leasta pairTopic filter and QoS levelfield combination.no payloadof
SUBSCRIBE reportthe message is a protocol violationof [MQTT-3.8.3-3]。about error handlingplease see the information on handling 4.8 section.
the maximum service requestedQuality of Service level fieldencoded as a wordbyte, after itfollows UTF-8 editthe topic name of the code,those topic filters /and
QoS level combinationare packed consecutively.
legend 3.22 – SUBSCRIBE messagepayloadFormatting
Description
7
6
5
4
3
2
1
0
Topic filter
byte 1
length MSB
byte 2
length LSB
bytes 3..N
Topic filter(Topic Filter)
quality of service requirements (Requested QoS)
reserved bit
Quality of Service level
byte N+1
0
0
0
0
0
0
X
X
the current version of the protocoldid not use the serviceQoS requirement (Requested QoS)the high six bits of the byte. If the Payloadany in the payloadbit is non-
zero value,or QoS Not equal 0,1 or 2, the serverRequiredconsider SUBSCRIBE packet isinvalid unionclose the network connection [MQTT-
3-8.3-4]。
3.8.3.1 payloadpayload non-normativeExample
legend 3.23 – payload wordbyte format non-standardexample displayalready Table 3.5 – Yesnon-normative payloadExample briefly described in
SUBSCRIBE reportthe packet's payload。
Table 3.5 – payloadpayload is notnormative example
topic name
“a/b”
Quality of Service requirements
0x01
topic name
“c/d”
Quality of Service requirements
0x02
legend 3.23 – validpayloadbyte format non-specification showsExample
Description
7
6
5
4
3
2
1
0
Topic Filter (Topic Filter)
byte 1
Length MSB (0)
0
0
0
0
0
0
0
0
byte 2
Length LSB (3)
0
0
0
0
0
0
1
1
byte 3
‘a’ (0x61)
0
1
1
0
0
0
0
1
MQTT-3.1.1-CN 39
byte 4
‘/’ (0x2F)
0
0
1
0
1
1
1
1
byte 5
‘b’ (0x62)
0
1
1
0
0
0
1
0
quality of service requirements (Requested QoS)
byte 6
Requested QoS(1)
0
0
0
0
0
0
0
1
Topic Filter (Topic Filter)
byte 7
Length MSB (0)
0
0
0
0
0
0
0
0
byte 8
Length LSB (3)
0
0
0
0
0
0
1
1
byte 9
‘c’ (0x63)
0
1
1
0
0
0
1
1
byte 10
‘/’ (0x2F)
0
0
1
0
1
1
1
1
byte 11
‘d’ (0x64)
0
1
1
0
0
1
0
0
quality of service requirements (Requested QoS)
byte 12
Requested QoS(2)
0
0
0
0
0
0
1
0
3.8.4 response
the server receives the clientone sent by the endpoint SUBSCRIBE when the message,RequiredUsage SUBACK packet response [MQTT-3.8.4-1]。
SUBACK messageRequiredand waiting for acknowledgment SUBSCRIBE messagehave the same packet identifiersymbol [MQTT-3.8.4-2]。
allows the server to sendsend SUBACK reportbefore the messagethen start sending and subscribingmatching PUBLISH packet.
If the server receivesa SUBSCRIBE packet, packetThe topic filter of an existing subscriptionmatching the topic filtersame,thenRequired
use the new subscription to completelyreplaces the existingsubscription. The topics of the new subscriptionthe filter and the previousthe same as the subscription,but itthe maximum QoS Valuecan not
same.That matches this topic filterany existing retainedretained messageRequiredis retransmitted,but the publish flowcannotMediumbreak [MQTT-3.8.4-3]。
if the topic filterdifferent from any existingstore subscription filters, the serverthe server will create aa new subscription and send allmatching retainedmessage.
If the server receivescontaining multiple topicsof the filter SUBSCRIBE packet,itRequiredas if it had received a seriesof multiple SUBSCRIBE
treat the message the same, thenone,exceptneed to combine their responsesmerged into a singleindependent SUBACK messagesend [MQTT-3.8.4-4]。
the server sends to the clientof the client SUBACK reporttext paireach pair of topic filters and QoS waitall levelsRequiredcontains a return code.Thisreturn
codeRequiredindicates that the subscription is grantedthe maximum granted QoS level,orindicates that this subscription failed [MQTT-3.8.4-5]. The server canto grant than
lower than the subscriber's requirementsome of QoS level.sent in response to the subscriptionof the sent messageof the payload QoS Requiredis the original published message's
QoS and servicegranted by the endpoint QoS of the twominimum value. If the original messageinformation QoS Yes 1 and the maximum granted QoS Yes 0, allowallow server
The server resends aa copy of the messageto the subscriber [MQTT-3.8.4-6]。
non-normativeExample
for a particular topictopic filter,ifcurrently subscribedthe client is grantedthe maximum QoS waitlevel is 1, thenmatching this filter
filter's QoS level 0 the application message will be according to QoS level 0 delivered to this client.this means the clientthe client will receive at most this
MQTT-3.1.1-CN 40
a copy of the message. On the other hand,that is, publishing to the sameof a topic QoS level 2 of the messagewill be downgraded by the server to QoS wait
level 1 redistribute toclient, therefore the clientthe client may receiveduplicate messagescopy.
If the currently subscribedthe client is grantedthe maximum QoS level is 0, thenoriginally by QoS level 2 published toclient application
message can, when busy,may be lost,Butthe server should notshould send duplicatemessage copy. Publish to the sameof a topic QoS level
1 message in transitwhen delivering to the client canmay be lost or duplicated.
non-normativecommentary
Usage QoS level 2 subscribeSubscribe to a topic filter equal tothat is:
I want to publish according to themtime's
QoS
level accepts matching thisitems
the filter's message
. This means,determinepossible during message deliverymaximum QoS waitlevel is the publisherresponsibility, andsubscriber can
requires the server to reduce QoS to more suitableconforms to its level.
3.9 SUBACK – subscription acknowledgment
the server sends SUBACK packet to the client, used to acknowledge ithas received and isin processing SUBSCRIBE packet.
SUBACK messagecontains a returncode list, theyspecified SUBSCRIBE pleaserequest'seach subscription isthe maximum granted QoS waitlevel.
3.9.1 fixed header
legend 3.24 – SUBACK packet fixed header
Bit
7
6
5
4
3
2
1
0
byte 1
MQTT control packetmessage type (9)
reserved bit
1
0
0
1
0
0
0
0
byte 2
remaining length
remaining lengthlength field
equal to the variable header'slength plus payloadthe length of the payload.
3.9.2 variable header
the variable header contains etc.pending acknowledgment SUBSCRIBE reporttext'spacket identifier.legend 3.25 – SUBACK reportPacket Variable Header describes possible
the format of the variable header.
legend 3.25 – SUBACK packet variable header
Bit
7
6
5
4
3
2
1
0
byte 1
packet identifier MSB
byte 2
packet identifier LSB
MQTT-3.1.1-CN 41
3.9.3 payload
the payload contains aa return code list. Each return codecorresponds to pending acknowledgementof SUBSCRIBE one of the packetsa topic filter. Return
order of codesRequiredand SUBSCRIBE messagein the order of the topic filterssame [MQTT-3.9.3-1]。
legend 3.26 – SUBACK reportpacket payloadFormatting describesin the payload a singlebyteencoded returncode field.
legend 3.26 – SUBACK packet payload format
Bit
7
6
5
4
3
2
1
0
return code
byte 1
X
0
0
0
0
0
X
X
Allowed return code values:
0x00 - maximum QoS 0
0x01 - success – maximum QoS 1
0x02 - success – maximum QoS 2
0x80 - Failure failure
0x00, 0x01, 0x02, 0x80 outsideof SUBACK returnreturn code is reservedof,cannotUsage [MQTT-3.9.3-2]。
3.9.3.1 payloadpayload non-normativeExample
legend 3.27 -payloadnon-normative byte format example shows in Table 3.6 -Yesnon-normative payload example briefly described
SUBACK messageof the payload.
Table 3.6 -payloadnon-normativeExample
Success - Maximum QoS 0
0
Success - Maximum QoS 2
2
Failure
128
legend 3.27 -payloadbyte formatNon-normative example
Description
7
6
5
4
3
2
1
0
byte 1
Success - Maximum QoS 0
0
0
0
0
0
0
0
0
byte 2
Success - Maximum QoS 2
0
0
0
0
0
0
1
0
byte 3
Failure
1
0
0
0
0
0
0
0
3.10 UNSUBSCRIBE –Cancel subscription
client sends UNSUBSCRIBE messageto the server,used to unsubscribesubscribe topic.
MQTT-3.1.1-CN 42
3.10.1 fixed header
legend 3.28 – UNSUBSCRIBE packet fixed header
Bit
7
6
5
4
3
2
1
0
byte 1
MQTT control packet type (10)
reserved bit
1
0
1
0
0
0
1
0
byte 2
remaining length
UNSUBSCRIBE reporttext fixedthe fixed header's 3,2,1,0 bit is to maintainReserved bit andRequiredset separatelyis 0,0,1,0。Server-sideRequiredconsiders anyits
its values are all invalidlegal and close the networknetwork connection [MQTT-3.10.1-1]。
remaining lengthlength field
equal to the variable header'slength plus payloadthe length of the payload.
3.10.2 variable header
The variable header contains aa packet identifier。2.3.1 sectionprovides information aboutmore about packet identifiersinformation.
legend 3.29 – UNSUBSCRIBE packet variable header
Bit
7
6
5
4
3
2
1
0
byte 1
packet identifier MSB
byte 2
packet identifier LSB
3.10.3 payload
UNSUBSCRIBE of the packetvalidpayload contains clientthe topics the client wants to unsubscribe fromtopic filter list。UNSUBSCRIBE in the packet
topicFilterRequiredis packed contiguously,according to 1.5.3 section specifiessemantic UTF-8 editcode string [MQTT-3.10.3-1]。
UNSUBSCRIBE of the packetvalidpayloadRequiredat leastcontainsa message filter. No payloadpayload's UNSUBSCRIBE packet is
violating the protocol [MQTT-3.10.3-2]. There isMore information about error handlingplease see 4.8 section.
3.10.3.1 payload non-conformingscopeExample
legend 3.30 -payloadNon-normative byte formatExample shows Table 3.7 -validNon-normative payload example briefly described
UNSUBSCRIBE of the packetvalidpayload.
Table 3.7 -payloadnon-normative exampleExample
Topic filter
“a/b”
Topic filter
“c/d”
MQTT-3.1.1-CN 43
legend 3.30 -payloadbyte formatnon-normativeexample
Description
7
6
5
4
3
2
1
0
Topic filter
byte 1
Length MSB (0)
0
0
0
0
0
0
0
0
byte 2
Length LSB (3)
0
0
0
0
0
0
1
1
byte 3
‘a’ (0x61)
0
1
1
0
0
0
0
1
byte 4
‘/’ (0x2F)
0
0
1
0
1
1
1
1
byte 5
‘b’ (0x62)
0
1
1
0
0
0
1
0
Topic filter
byte 6
Length MSB (0)
0
0
0
0
0
0
0
0
byte 7
Length LSB (3)
0
0
0
0
0
0
1
1
byte 8
‘c’ (0x63)
0
1
1
0
0
0
1
1
byte 9
‘/’ (0x2F)
0
0
1
0
1
1
1
1
byte 10
‘d’ (0x64)
0
1
1
0
0
1
0
0
3.10.4 response
UNSUBSCRIBE reporttext mentionprovided topic filter (regardless of whether it containswildcard)Requiredwith this held by the serverclient's currentmain
topic filter set one by onea character comparison.if any filter completelyexact match,then it (the serverserver) its ownThe subscription will be deleted,Otherwise
there will be no furtherprocessing [MQTT-3.10.4-1]。
If the server deletesa subscription:
itRequiredstop delivering any new messagesmessage to this clientclient [MQTT-3.10.4-2]。
itRequiredcomplete delivery of any alreadystarts sending to the clientsent by the endpoint QoS 1 and QoS 2 of the message [MQTT-3.10.4-3]。
itYescontinue sending any existingpreparing to distributeto the client's bufferstore message.
Server-sideRequiredsend UNSUBACK packet responseclient's UNSUBSCRIBE request.UNSUBACK messageRequiredcontains and
UNSUBSCRIBE reporttext phasethe same packet identifier [MQTT-3.10.4-4]。even ifdid not delete anyany topic subscription,the server alsoRequiredemit
send a SUBACK response [MQTT-3.10.4-5]。
If the server receivescontaining multiple topicsof the filter UNSUBSCRIBE packet,itRequiredas if it received a series ofmultiple
UNSUBSCRIBE reportone texthandle that packet in the same way,besidesmerge their responses into onea separate UNSUBACK outside the message.
[MQTT-3.10.4-6]。
3.11 UNSUBACK – Cancel subscriptionacknowledgment
the server sends UNSUBACK messageto the client to confirm receiptto UNSUBSCRIBE packet.
MQTT-3.1.1-CN 44
3.11.1 fixed header
legend 3.31 – UNSUBACK message fixedfixed header
Bit
7
6
5
4
3
2
1
0
byte 1
MQTT control packetmessage type (11)
reserved bit
1
0
1
1
0
0
0
0
byte 2
remaining length (2)
0
0
0
0
0
0
1
0
remaining lengthlength field
indicating the variable header'slength, for UNSUBACK this messagea value equals 2。
3.11.2 variable header
the variable header contains etc.pending acknowledgment UNSUBSCRIBE messagethe packet identifier.
legend 3.32 – UNSUBACK Message canvariable header
Bit
7
6
5
4
3
2
1
0
byte 1
packet identifier MSB
byte 2
packet identifier LSB
3.11.3 payload
UNSUBACK message has nopayload。
3.12 PINGREQ – heartbeat request
client sends PINGREQ messageto the server. Useat:
1. in the absence of any othercontrol packet from clientwhen the client sends to the server,inform the server that the clientclient is alive.
2. request the server to send response confirms it is stillalive.
3. use the network to acknowledgenetwork connection has nodisconnect.
Keep Alive (Keep Alive)processingused inthis packet,detailedfor information, see 3.1.2.10 section.
3.12.1 fixed header
legend 3.33 – PINGREQ packet fixed header
Bit
7
6
5
4
3
2
1
0
byte 1
MQTT control packet type (12)
reserved bit
MQTT-3.1.1-CN 45
1
1
0
0
0
0
0
0
byte 2
remaining length (0)
0
0
0
0
0
0
0
0
3.12.2 variable header
PINGREQ reportThe message has no variable header。
3.12.3 payload
PINGREQ reportthe message has no payload。
3.12.4 response
Server-sideRequiredsend PINGRESP packet responseclient's PINGREQ message [MQTT-3.12.4-1]。
3.13 PINGRESP – heartbeat response
the server sends PINGRESP packet responds to the clientof the client PINGREQ packet.Representsserver is still alive-ing.
Keep Alive (Keep Alive)processingused inthis packet,detailsplease see 3.1.2.10 section.
3.13.1 fixed header
legend 3.34 – PINGRESP message fixedfixed header
Bit
7
6
5
4
3
2
1
0
byte 1
MQTT control packet type (13)
reserved bit
1
1
0
1
0
0
0
0
byte 2
remaining length (0)
0
0
0
0
0
0
0
0
3.13.2 variable header
PINGRESP messageno variable headerheader.
3.13.3 payload
PINGRESP messagehas no Payloadpayload.
3.14 DISCONNECT –disconnect
DISCONNECT the packet is sent from the client to the serverserver's lasta control packet.indicates that the client disconnected normallyconnection.
MQTT-3.1.1-CN 46
3.14.1 fixed header
legend 3.35 – DISCONNECT messagefixed header
Bit
7
6
5
4
3
2
1
0
byte 1
MQTT control packet type (14)
reserved bit
1
1
1
0
0
0
0
0
byte 2
remaining length (0)
0
0
0
0
0
0
0
0
Server-sideRequiredverify all retainedreserved bits are all setset to 0, ifthey are not 0 Requireddisconnect [MQTT-3.14.1-1]。
3.14.2 variable header
DISCONNECT The packet has no variable header.
3.14.3 payload
DISCONNECT packet has no payloadpayload.
3.14.4 response
client sends DISCONNECT reportafter the message:
Requiredclose the network connection [MQTT-3.14.4-1]。
cannotthrough that network connection againsend any controlcontrol packet [MQTT-3.14.4-2]。
server upon receiving DISCONNECT when sending a message:
Requireddiscard any associated with the current connectionassociated unsentpublishedwillmessage, see the specific description 3.1.2.5 section [MQTT-3.14.4-3]。
shouldClose the network connection,if the client has not yet done so.
MQTT-3.1.1-CN 47
4 operational behavior
4.1 state storage
To provide quality of serviceQoS guarantee, clientclient and server havenecessary to store sessionstate. Throughout the sessionbetween, the clientclient and serverallRequired
store session state [MQTT-4.1.0-1]. SessionRequiredlasts at least as long as its active networknetwork connection equally longtime of [MQTT-4.1.0-2]。
the server's retained messagemessage is not session statepart of the state. Servershouldretain that kind of messagemessage until the client deletes it.
non-normativecommentary
client and serverimplementation's storageCapacitynecessarily limitedof, may also need tosubject to management policyrestrictions, such as acrossnetwork connection's session
the maximum storage of session statestorage time. already retainedstored session stateThe loss may be a certaincaused by a management operation,for example, fora predefined item
automatic response.the consequences it causesis session termination. These operations maybe resource constraintsor caused by other operational reasonsof. Need
Need to carefully evaluate the clientclient and serverof storage capacity,to ensure storage spacetime is sufficient.
non-normativecommentary
client or serverof software and hardware failuresmay all cause the session state toof loss or corruption。
non-normativecommentary
server and clientnormal operation maymeaning that the saved statestate loss or corruptionis management operations or software/hardwarecaused by failures.
administrative operations may befor a predefinedautomatic response to conditions. Thissome operations may beresource limitations or other operationstriggered by the reason.
for example, the server canmay be based on externalconditions, decide notto send a certain message againor some messages distributed to anyany current orafter the client
client.
non-normativecommentary
MQTT user shouldshould evaluate MQTT client and server implementationsof storage capacity,ensure that it can satisfy the needrequest.
4.1.1 Non-normative example
for example, if you want to collectthe use of meter readingsthe user may decide to use QoS 1 levelthe message, because they cannotreceiving data on the networknetwork transmission path
lost in ..., but,They may thinkclient and server datadata can be stored inmemory (volatile memory), because (they think
the power supply isvery reliable,will not have too greatrisk of data loss.
in contrast, parkingbilling and payment applicationsthe provider may decide anyunder no circumstancescan cause data delivery messages to be lostloss,Thereforethey require that
transmitted over the networkbefore, all datadata must be written tonon-volatile storagedevice (such as a hard disk)。
4.2 Network Connection
MQTT protocol needsrequire the underlying transportlayer can provideordered, reliableof,bidirectionaltransport (from the client toServer-side and fromserver to client
byte stream of the endpoint).
non-normativecommentary
MQTT 3.1 makethe transport layer protocol usedYes [RFC793] defined TCP/IP cooperatediscussion.the following protocol alsosupports:
MQTT-3.1.1-CN 48
TLS Protocol [RFC5246]
WebSocket Protocol [RFC6455]
non-normativecommentary
TCP port 8883 and 1883 already in IANA Noteregistration, respectively used for MQTT of TLS and non- TLS communication.
connectionless network transmissiontransport protocol such as UDP Yesnot supported,because they maymay lose datapacket or reorder data packets。
4.3 Quality of service level and protocol flow
MQTT according to thisservice defined inservice quality (QoS) level distribution applicationMessage. Distributionthe protocol is symmetric, in the followingin the above description,client
and the server can boththe sender can alsoIt is already the receiver.The delivery protocol focuses onis from a single sender tosingle receiver'sApplication message.clothes
serverDistribute application messages to multiple clientswhen at the end, each clientclient processes independently. Delivered to the clientthe client's outbound applicationmessages and inbound application messages
of QoS level cancan be different.
the following non-normative flowThe diagram shows possibleimplementation methods.。
4.3.1 QoS 0:at most once
message delivery depends onof the underlying networkcapabilities. The receiverwill not send a response, the sender also does notwill retry. The messagemay be delivered once or may
was not delivered at all.
for QoS 0 ofdelivery protocol, the sendersender
Requiredsend QoS equals 0,DUP equals 0 of PUBLISH message [MQTT-4.3.1-1]。
for QoS 0 ofdelivery protocol, the receiverreceiver
Accept PUBLISH when a message, simultaneously receivereceive all of the messageright.
legend 4.1 – QoS 0 protocol flowdiagram,non-normativeExample
senderaction
control packet
receiveraction
PUBLISH message QoS 0, DUP=0
---------->
deliver application messages toappropriate subsequent receiverreceive
the one(s)
4.3.2 QoS 1: at leastDividesend once
clothesaffairqualityquantityconfirmprotecteliminatebreathTofewsendreachonetimes。QoS 1 of PUBLISH reporttextofcanchangereportheadMediumPackagecontainoneitemsreporttextmarkknowsymbol,Needwant
PUBACK messageacknowledgment.2.3.1 sectionprovides information about packet identifiersmore information about the identifier。
for QoS 1 ofdelivery protocol, the sendersender
each time a new application message is sentall messagesRequiredAssign an un-the packet identifier usedcharacter.
sent PUBLISH messageRequiredcontainsmessage identifier and QoS equals 1,DUP equals 0。
MQTT-3.1.1-CN 49
Requiredthis PUBLISH reportmessage regarded as
unacknowledged
,untilreceives the corresponding one from the receiver PUBACK packet.4.4 section
there is a ... about unacknowledgeddiscussion of message acknowledgment。
[MQTT-4.3.2-1].
once the sender receives PUBACK packet,Thispacket identifiercan be reused.
Note:Allowedthe sender is waiting for an acknowledgmentwhen using differentpacket identifier to send subsequentof PUBLISH packet.
for QoS 1 ofdelivery protocol, the receiverreceiver
response PUBACK messageRequiredcontains amessage identifiers,this identifier comes fromfrom the received,already accepted allof authority
PUBLISH packet.
sent PUBACK reportafter the message,the receiver mustany containing the sameinbound packet identifier PUBLISH messageas a
a new message, andignore its DUP markflag value.
[MQTT-4.3.2-2].
legend 4.2 – QoS 1 protocol flowdiagram,non-normativeExample
senderaction
control packet
receiveraction
store messages
send PUBLISH message QoS=1,
DUP=0, with the messageIdentifiers
---------->
start the application message's ...subsequent distribution
1
<----------
send PUBACK message, with a messagemark
identifier
discard message
1
does not require the receiver tosend PUBACK before complete distributionsend application messages. The originalsender receives PUBACK messageafter that,
all of the application messagerights will be transferred tothis receiver.
4.3.3 QoS 2: onlydeliver once
this is the highest level ofquality of service,Messageloss and duplicationall are unacceptableof. Using this quality of servicethe quality level will have extraadditional overhead.
QoS 2 of eliminationin the message variable headerhas a packet identifier.2.3.1 sectionprovides information aboutupdate of the packet identifiermore information.QoS 2 of PUBLISH
the receiver of the packet usesusing a two-step acknowledgmentacknowledgment process to confirm receipt.
for QoS 2 ofdelivery protocol, the sendersender
must assign to the to-be-sent ...new application message distributionassign an unused packetidentifier.
sendof PUBLISH messageRequiredcontainspacket identifier and the packet's QoS equals 2,,DUP equals 0。
Requiredthis PUBLISH reportmessage regarded as
unacknowledged
,untilreceives the corresponding one from the receiver PUBREC packet.4.4 section
there is a ... about unacknowledgeddiscussion of message acknowledgment。
MQTT-3.1.1-CN 50
received PUBREC after the messageRequiredsend a PUBREL packet.PUBREL message mustmust contain the sameoriginal PUBLISH message
samethe packet identifier.
Requiredthis PUBREL reportmessage regarded as
unacknowledged
,untilreceives the corresponding one from the receiver PUBCOMP packet.
once the corresponding ... has been sentof PUBREL message thencannotresend this PUBLISH packet.
[MQTT-4.3.3-1].
once the sender receives PUBCOMP message, thisthe packet identifier can then be reused。
Note:Allowedthe sender is waiting for an acknowledgmentwhen using differentpacket identifier to send subsequentof PUBLISH packet.
forQoS 2delivery protocol, receiveperson
response PUBREC messageRequiredcontainspacket identifier, this identifierfrom the received, already accepted allauthorized
PUBLISH packet.
Upon receiving the corresponding PUBREL before the message,receiverRequiredsend PUBREC reportconfirmationany subsequent packet with the samesame identifier
of PUBLISH packet. In this case,itcannotduplicate delivery of messagesto any subsequentreceiver.
response PUBREL of the packet PUBCOMP messageRequiredcontaining and PUBREL reportmessage with the same identifiercharacter.
send PUBCOMP reportof the textafter, the receivermust include the sameany with the same message identifierfollow-up PUBLISH reporttext shouldmake one
a new publication.
[MQTT-4.3.3-2].
legend 4.3 – QoS 2 protocol flowdiagram,non-normativeExample
senderaction
control packet
receiveraction
store messages
send PUBLISH packet,QoS=2,
DUP=0, withpacket identifier
---------->
Methods A: store messages, or methods B:
store the packet identifier, then begin tobefore
deliver this application messagebreath
1
。
send PUBREC reporttext,with message identifier
identifier.
<----------
discard the message, store PUBREC in
packet identifier
send PUBREL reporttext, with messagemark
identifier
---------->
MQTT-3.1.1-CN 51
Methods A: starts to forward the application messagebreath
1
then discard the message or method B:discard
packet identifier
send PUBCOMP packet,with message
Identifiers
<----------
discard the saved statecondition
1
does not require the receiverwhen sending PUBREC or PUBCOMP beforecomplete distribution shouldwith the message. The original sendingreceiver receives
PUBREC reportafter the packet, the application messagethe ownership of the message thenwill be transferred to this receiver。
legend 4.3 – QoS 2 Protocolflowchart, non-standardexample displaythe receiver's QoS 2 waittwo types of level messageshandling method.they
the difference is what the message ...when can startstart distribution. Implementationthe implementer can decide to usewhich method to use. As long as the implementationthe implementer only selecteda method
method,will not affect QoS flowprocess reliability.
4.4 message delivery retry
the client sets the Clean Start flagsession (CleanSession)Flagsis 0 reconnectwhen, the clientand the serverRequireduse the originalresend the initial message identifier
any unacknowledged PUBLISH message (if QoS>0) and PUBREL message [MQTT-4.4.0-1]. This is the onlyoneRequirementclient or
Server resends messagesthe situation.
non-normativecommentary
Retransmission of control packetsneeded to overcomesome outdated TCP data on the networkdata loss problem.deployed in those environments MQTT
3.1.1 realImplementation may still be neededfocus on this issuetopic.
4.5 message received
The server takes over inboundownership of the application messagewhen authorized, itRequiredthe messageadd to subscriptionthe session of the matching clientin the state.matching rules determine
semantic view 4.7 section [MQTT-4.5.0-1]。
Under normal circumstances, the clientclient receives sentto its subscriptionmessage. Clientmay also receive messages not related to itthe subscription exactly matchesmatching message. For example
If the server automatically sendsthe client assigneda subscription,possiblethis situation occurssituation. Currently processing UBSUBSCRIBE requestmay also receiveto
message. ClientRequiredaccording to the possibleservice quality usedquantity (QoS) rule confirms that it receivedany PUBLISH packet,regardlessitSelectwhether to process
Process the application message contained in the packetuse message [MQTT-4.5.0-2]。
4.6 message ordering
Implement what is defined in this chapterduring the protocol flow,clientRequiredfollow the following rulesthen:
Resend any previous PUBLISH reportwhen the message,Requiredaccording to original PUBLISH messagethe sending orderresend in order (applicableused for QoS 1 and
QoS 2 Message)[MQTT-4.6.0-1]。
Requiredaccording to the corresponding PUBLISH Send the packets in order PUBACK reporttext (QoS 1 Message)[MQTT-4.6.0-2]。
Requiredaccording to the corresponding PUBLISH Send the packets in order PUBREC message (QoS 2 Message)[MQTT-4.6.0-3]。
Requiredaccording to the corresponding PUBREC Send the packets in order PUBREL message (QoS 2 Message)[MQTT-4.6.0-4]。
Server-sideRequiredby default considers eachtopics all haveorder. ItYesprovide aa management function orother mechanisms, toallows one ormultiple masters
Treat the topic as unordered [MQTT-4.6.0-5]。
MQTT-3.1.1-CN 52
The server handles sendingto ordered topicswhen a message,Requiredas abovethe rules will messagemessage distributed to each subscriber. In addition, itRequiredaccording to
Received from the clientsend in order PUBLISH reportmessage to consumer(for the same topicquestion and QoS)[MQTT-4.6.0-6]。
non-normativecommentary
The rules listed aboveensure, using QoS 1 publishand subscription message flow,subscribers according to the messagethe order at message publicationreceived in ordereach
MessageThe final copy, but the message canmay be repeated, thismay cause it tothe successor messagesafter receiving a certain alreadyalready received message
Re-sent version. For example, the publisher in ordersequence 1,2,3,4 Send messages, subscribethe order received by the receivermay be 1,2,3,2,3,4。
If the client and serverthe server can guarantee anyat any time, at most one messageinformation is in
during transmission (
in-flight
)
(in a certain messagebefore the message is acknowledged
Do not send the followingmessage), thenwhat,Will notYes QoS 1 of the messagewill be in any of itsreceived after subsequent messages。 For example,
The order in which subscribers receiveorder may be 1,2,3,3,4, rather than 1,2,3,2,3,4. The transmission window (in-flight window) letis 1
Means that, in the sameon a topic,even ifpublisher sendsa series of different QoS levels of messages,their order is alsobe protected
keep.
4.7 topic name and topic filter
4.7.1 topic wildcard
topiclevel (topic level) separatedseparator used to structureNormalization introduces topic names.if there is distributionseparator, it will the mainSplit the topic name into multiple
topic level
level
topic level 。
Subscribed topic filterthe device can contain specialspecial wildcards, allowing yousubscribe to multiple at oncetopic.
The topic filter mayto use wildcards, but topic namescannotUsagewildcard [MQTT-4.7.1-1]。
4.7.1.1 topic levelDelimiters
slash(‘/’ U+002F) used forEach of the topic levelsTier, to provide a hierarchy for the topic namestructure. When the clientclient subscribes to the specifiedtopic filter
The filter contains two wildcardswhen the separator, the topic levellevel separator is veryuseful. The topichierarchy separator cancan appear in topic filtersor the topic name's
Any position. Adjacentthe topic hierarchyseparator represents azero-length topiclevel.
4.7.1.2 multi-layerwildcard
numeric flag (‘#’ U+0023) is usedfor matching in topicsAnyTierthe wildcard. Multi-levelwildcard represents itsparent and any numberchild of the amount
Levels. Multi-level wildcardseparator must be located at itsits own level or followed bytopic level separatorafter the separator. Regardlesswhich kind of situationsituation, it alwaysRequiredis the subject
The last of the filtercharacters [MQTT-4.7.1-2]。
non-normativecommentary
For example,ifThe client subscribes to topics “sport/tennis/player1/#”,It will receive using the followingthe topic name publishedMessage:
“sport/tennis/player1”
“sport/tennis/player1/ranking”
“sport/tennis/player1/score/wimbledon”
non-normativecommentary
“sport/#”also matchesseparate “sport” , because # includingits parent.
“#”is validof,will receive allapplication message。
“sport/tennis/#”alsois valid.
“sport/tennis#”is invalid.
MQTT-3.1.1-CN 53
“sport/tennis/#/ranking”Yesinvalid.
4.7.1.3 single-layer passmatching character
plus sign (‘+’ U+002B) can only usefor a single topic levellevel-matching wildcardcharacter.
In the topic filterany level cancan use a single-level wildcard,including thefirst and last levels. HoweveritRequiredoccupies the filter's
the entire level [MQTT-4.7.1-3]。Can be in the topic filtermultiple levels in thelevel, using it,can also be used with multi-leveluse wildcards togetheruse.
non-normativecommentary
For example, “sport/tennis/+” match “sport/tennis/player1” and “sport/tennis/player2” ,Butdoes not match
“sport/tennis/player1/ranking” . Meanwhile, sincesingle-level wildcard onlycan match one levellevel, “sport/+” does not match
“sport” but it matchesallocate “sport/”。
non-normativecommentary
“+” is valid.
“+/tennis/#” is valid.
“sport+” is invalid.
“sport/+/player1” is also valid.
“/finance” match “+/+” and “/+” , but notmatch “+”。
4.7.2 with$topics beginning with
Server-sidecannotwill $ character startsleading topic name matchmatch wildcard (#or+) openTopic filter beginning with [MQTT-4.7.2-1]The server shouldprevent
The client uses this kind oftopic names and otherclients exchange messagesmessage. The server implementation canwill $ Topic names beginning withfor other purposes.
non-normativecommentary
$SYS/ is widely"Used to contain server-specific informationmessage or control interfacethe prefix of the topic。
Applications cannot use $ topic names beginning with the charactertopic.
non-normativecommentary
Subscription “#” The client will not receiveTo any published to “$” beginning subjectthe topic's messages.
Subscription “+/monitor/Clients” the client does notwill receive any messages sentdistribute to “$SYS/monitor/Clients” of eliminationmessage.
Subscription “$SYS/#” the clientwill receive messages published to “$SYS/” beginningmessages on the topic.
Subscription “$SYS/monitor/+” ofThe client will receive a Publishto “$SYS/monitor/Clients” mainthe topic's messages.
If the client wants towhen accepting “$SYS/” topic starting withmessages and not starting with $ topic starting withmessages, it needs toat the same time
Subscription “#” and ““$SYS/#”。
4.7.3 topicsemanticand usage
topic name and topic filterFilters must conform tothe following rules:
all topic names andTopic filterRequiredat least includecontains one character [MQTT-4.7.3-1]。
topic name and topic filterFilters are case-sensitivelowercase.
topic name and topic filterFilters can containspace.
MQTT-3.1.1-CN 54
topic name or topic filterFilters with leading ortrailing slash “/” distinguish.
contains only slashes “/” the topic name or topic filterThe filter is valid.
topic name and topic filterfiltercannotcontains a null character (Unicode U+0000) [Unicode] [MQTT-4.7.3-2]。
topic name and topic filterfilter is UTF-8 Encoded string, theycannotExceeded 65535 byte [MQTT-4.7.3-3]. see 1.5.3
section.
exceptcannot exceed UTF-encoded characterstring length limitIn addition, the topic name or topicthe levels of the filterquantity has noother restrictions.
when matching subscriptions, the serverservercannotfor topic name orThe topic filter executesperform any normalization(normalization) process, notcan modify or replace
any unrecognized charactersymbol [MQTT-4.7.3-4]. SubjectEach non-wildcard in the filterwildcard levels need to be matched one by onecharacters match the topiccorresponding level in the name
level is considered a successful match。
notSpecificationcommentary
Usage UTF-8 The encoding rules mean, the topic filterand the comparison of topic namesThe comparison can be made by comparingcompared to the encoded UTF-8 byteor solution
encoded Unicode characters.
notSpecificationcommentary
“ACCOUNTS” and “Accounts” are different subjectsTitle.
“Accounts payable” is consistentthe subject name of the
“/finance” and “finance” are different.
ifThe subscribed topic filter and messagetopic name matching, application messages willbe sent to eachmatching clientsubscription. Topicmay be
Administrator at the serverpredefined, or it may be the serverserver receives the firsta subscription or using that topicapplication message with the topic namedynamically added when the message is received
of. The server may alsocan use a securitysecurity component selectivelyauthorize the client to use a certaintopic resource.
4.8 Error Handling
Unless otherwise specified,If the server orThe client encounteredBehavior that violates the protocol,itRequireddisable transmission of thisa protocol violationthe network of control messages
network connection [MQTT-4.8.0-1]。
client or serverimplementation may encountertransient errors (Transient Error)(e.g., insidethe buffer is fullcase) leading tocannot successfully
processing MQTT packet.
If the client or serverserver side processes inboundencountered a transient when processing a control packettime error,itRequiredclose the transport thatNetwork connection for control packetsJie
[MQTT-4.8.0-2]。ifthe server detectedtransient error, itshould notdisconnectconnect or executeany to other clientsoperations affecting the peer
do.
MQTT-3.1.1-CN 55
5 security
5.1 Overview
The content of this chapter is forreference, is non-standardized. However, strongly recommended tosupply TLS of serviceserver-side implementationshouldUsage TCP port 8883
(IANA service name:secure-mqtt)。
solution providerNeed to consider manyrisks. For example:
Devices may be stolenuse
client and serverthe static data maymay be accessible (may be fixedmodify)
Protocol behavior may haveside effects (such astiming attacks)
denial-of-service attacks
Communications may be interceptedintercept,modifyredirection or disclosure
bogus control messagesinjection
MQTT scheme throughoften deployed insecure communicationenvironment. In thiscase, the protocolimplementation usually needsIt is necessary to provide these mechanisms:
User and device identityauthentication
Server resource accessauthorization
MQTT control packettext and embedded applicationthe integrity of the dataintegrity verification
MQTT control packettext and embedded applicationthe privacy of the dataprivate control
As a transport layer protocol,MQTT Focus only on message transmission,provide appropriate securityfull functionality is the implementer's responsibilityresponsibility. Use TLS [RFC5246] Yes
a relatively common choice. In addition to technicalapart from the security issues,and geographic factorsfactors (e.g., the United StatesEU Safe Harbor Principles
[USEUSAFEHARB]), industrystandards (e.g., thethird-party payment industrydata security standards [PCIDSS]), regulatoryconsiderations (Example
such as Sarbanes-profoundOxley Act [SARBANES]) etc.problem.
5.2 MQTT Solution: Security and Authentication
Protocol implementations may want tomust comply with specificindustrial security standards, such as NIST netcybersecurity framework [NISTCSF] , third-partypayment industry datapeace
full standard [PCIDSS] , U.S. federalinformation processing standards [FIPS1402] and NSA addcipher combination B [NSAB] 。
In MQTT of the patchsupplementary publication (MQTT and the NIST Framework for Improving Critical Infrastructure
Cybersecurity [MQTT NIST]) can be found inIn NIST Networkingsecurity framework [NISTCSF] MediumUsage MQTT ofguidance. Use
Industry certification, independentauditing and authentication technologyhelps to meetcompliance requirements.
5.3 Lightweight encryption and constrained devices
widely adopted advanced encryptionencryption standard [AES] numberdata encryptionStandard [DES] 。
recommended for use as restrictedlow-end device featuresspecially optimized lightweightlevel encryption internationalStandard ISO 29192 [ISO29192] 。
5.4 implementation considerations
implementation and use MQTT need to consider manysecurity issues.belowthe part should notshould be treated as aitems checklist 。
Protocol implementations may implementnow the following partpart or all:
MQTT-3.1.1-CN 56
5.4.1 client identityverify
CONNECT reporttext contains username and password fields.ImplementationCan decide how to use these charactersThe content of the paragraph. Implementers can provideown
Authentication mechanism,or use an externalauthentication system such as LDAP [RFC4511] or OAuth [RFC6749] , alsoCan utilize the operating system
authentication mechanisms.
implementations can transmit plaintextdeliver authentication data,obfuscate that data, or not requireany authentication data,but should be awarethis will increase the use of virtual between intermediateman-in-the-middle attack
attacks and replay attacksrisk.5.4.5 sectionintroduced the exactmethods to ensure data privacy.
On the client and serverendpointsvirtual private network (VPN) canensure that data is onlyAuthorized clientsthe client receives.
Usage TLS [RFC5246] when,The server can usesent by the client SSL certificateverify the clientidentity.
The implementation may allow the clientclient through the applicationmessage sending credentials to the servercertificate for identity verificationproof.
5.4.2 client authorization
Based on the client-providedinformation such as username, client identifieridentifier (ClientId)、clientthe hostname or IP address, orauthentication
The result, the servercan restrict access to certainserver resourcesaccess.
5.4.3 Servicesendpoint itselfidentity verification
MQTT protocol does notis two-way trustof, it does notprovide client verification of server identitymechanism.
ButUsage TLS [RFC5246] when, the client can use the servicesent by the server SSL certificateverify the serveridentity. From a single IP manydomain name
Provide MQTT The service implementation shouldconsider RFC6066 [RFC6066] No. 3 sectiondefined TLS of SNI Extension.SNI allows clientsend
Tell the server that it wants toconnected serverhostname.
The implementation may allow the serverserver through the applicationmessage sending credentials to the clientcertificate for identity verificationproof.
On the client and serverendpointsvirtual private network (VPN) canensure the clientconnects to the expectedof the server.
5.4.4 controlmessageand application messagemessage integrityintegrity
The application can be in the applicationthe message separately contains a hash value. Thisdoing so can PUBLISH controlthe network transmission and static dataprovide content
Integrity check.
TLS [RFC5246] mentionprovided for networkthe transmitted data isHash algorithm for integrity verificationmethod.
On the client and serverendpointsvirtual private network (VPN) connectionYou can VPN coveredThe network segment provides data integrityintegrity check.
5.4.5 control messages andapplication messagebreathconfidentiality
TLS [RFC5246] canfor network transmissionencrypted.. If the valid TLS cipher suitecombination contains encryptionalgorithm is NULL,then it
It does not encrypt data.must ensure the clientand the server'sconfidentiality, should avoid usinguses these cipher suitesagreement.
Applications can separately addto encrypt application messagescontent. This canProvide application messages in transitneutral and staticconfidentiality of static dataConfidentiality. But cannot provide application messages
Other attributes of the message, such astopic name encryption.
client and serverimplementations can encryptStoring static data, for examplecan encrypt application messagesmessage as part of a sessionstorage.
On the client and serverendpointsvirtual private network (VPN) connectionYou can VPN coveredThe network segment ensures the data'sprivacy。
5.4.6 message transmissionnon-repudiationauthenticity
The application designer mayneed to consider appropriatestrategies to implement end-to-enddeniability (non-repudiation)。
MQTT-3.1.1-CN 57
5.4.7 detectionclientclient and serverserver-sidetheft
Usage TLS [RFC5246] of the clientClient and server implementations shouldcan ensure,Initialize TLS [RFC5246] when connecting, provideprovided SSL prove
The certificate is bound to the hostname (clients need to connector the server will be connectedof) relationassociated.
Usage TLS [RFC5246] of the clientClient and server implementations canto choose to provide detectionCheck the certificate revocation list (CRLs [RFC5280]) and online
Certificate Status Protocol (OSCP) [RFC6960] offunction,Reject the use of revokedcertificate.
Physical deployment cantamper-resistant hardware andspecial data of application messagestransmission combination.For example,ainstruments maybuilt-in one GPS to ensure
Not in unauthorizedused in the region.IEEE security devicedevice authentication [IEEE 802.1AR] is to useto implement this mechanismA standard for control,it makes
Use encrypted binding identifierto verify device identitycopy.
5.4.8 detect abnormal behavior
The server implementation canmonitor the client'sbehavior, detect potentialsecurity risks. For example:
Repeated connection requests
Repeated authenticationrequest
Abnormal termination of the connection
Topic scan (requestsend or subscribe to largequantity topic)
Send undeliverablemessages (topics withoutsubscribers)
The client connects, butDo not send data
Discover security rule violationsthe behavior, the serverimplementation candisconnect the client connectionconnect.
The server implementation detectsunwanted behaviorcan be based on IP groundaddress or client identifierto implement aDynamic blacklist.
Service deployment can makeusing network layercontrol (if available) implemented based on IP groundaddress or otherRate limit of its informationor blacklist.
5.4.9 otherof securitysecurity precautionsitem
If the client or serverserver-side SSL Certificate loss, or IThey consider the certificate stolenused or revoked(Use CRLs [RFC5280] and
OSCP [RFC6960])ofsituation.
client or serverwhen verifying credentials,if it is found that the user'susername and password are lostor stolen, shouldshould revoke or reissue。
When using long-lived connections:
client and serverUsage TLS [RFC5246] should allowallow renegotiationnegotiate a session to confirmnew encryption parameters (replacesession key
Key, change the cipher suiteidentity, change authenticationcredentials).
The server can disconnectclient connection,and require them touse new credentials to re-verify identity.
On a restricted network, the trustedlimited to devices and clientsendpoint can use TLS session resumption [RFC5077] reduce TLS Sessionreconnect [RFC5246] of cost
cost.
Connected to the serverand other clientsclients connected to the serverend There is a trust transitive relationship between, they all have the righton the same topic
to publish messages.
MQTT-3.1.1-CN 58
5.4.10 Usage SOCKS broker
The client implementation shouldbe aware that some environmentsenvironment requires using SOCKSv5 [RFC1928] generationmanagement creates outboundnetwork connection.some MQTT real
Security can now be utilizedtunnel (such as SSH)Through SOCKS broker. oneAn implementation decides to support SOCKS when,They should simultaneously supporthide
of the name and username passwordcode verification SOCKS proxy.for the lattercase, implementshould be aware SOCKS cancan useplaintext authentication,
ThereforeShould avoid using the same credentialsconnection MQTT server.
5.4.11 security profile
Implementer and solution designdesigners may wishTreat security as a configuration fileset shouldapplied to MQTT in the protocol. The following describesis a layered security
overall hierarchical structure.
5.4.11.1 Opencommunication configuration
Use open communication configurationwhen setting,MQTT The protocol runs on a built-in without extraoverhead of the additional secure communication mechanismput on the network.
5.4.11.2 securitynetwork communication configuration
Use secure network communicationwhen configuring communicationMQTT protocol operationrun in a securecontrolled physical or virtualon the network,For example VPN or objectPhysical security network.
5.4.11.3 Secure transport configuration
Use secure transmission configurationwhen setting,MQTT protocol runs onUsage TLS [RFC5246] ofPhysical or virtual networkon the network, it providesProvides identity authentication,
Integrity and confidentiality。
Use built-in userUsername and password fields,TLS [RFC5246] client identityIdentity authentication can be usedfor (or instead of)MQTT guestclient authentication
proof.
5.4.11.4 Industry-standard securityfull configuration
As can be expected,MQTT Bydesigned to supportmany industry-standard applicationsconfiguration,Each defines aa threat model and for definingposition threat
The special security mechanism. Special securitymechanism recommends the following methodchoose in the plan:
[NISTCSF] NIST network security frameworkframe
[NIST7628] NISTIR 7628 Smart Grid Cybersecurity Guide
[FIPS1402] (FIPS PUB 140-2) encryption modulesecurity requirements
[PCIDSS] PCI-DSS Third-party supportPayment industry data securityfull standard
[NSAB] NSA encryptioncombination B
MQTT-3.1.1-CN 59
6 Usage WebSocket asnetwork layer
if MQTT In WebSocket [RFC6455] connectionon transmission,RequiredsatisfyThe following conditions:
MQTT control packettextRequiredUsage WebSocket binary numberData frame sent. Ifreceived any other type ofData frame, receive
personRequiredclose the network connection [MQTT-6.0.0-1]。
single WebSocket numberData frame can contain multipleone or part MQTT Packet. The receivercannotSuppose MQTT control packetpress
WebSocket frame boundary alignment [MQTT-6.0.0-2]。
clientRequiredThe string mqtt contained in itprovided WebSocket sub-protocolin the protocol list [MQTT-6.0.0-3]。
Server selects and returnsreturned WebSocket sub-protocolprotocol nameRequiredYes mqtt [MQTT-6.0.0-4] 。
Used to connect clientsand the server's WebSocket URI Pair MQTT has no effect on the protocol.
6.1 IANA Noteprecautions
this specification requests IANA In WebSocket sub-protocolRegistered under the protocol name entry WebSocket MQTT sub-protocol,Use the following data:
legend 6.1 - IANA WebSocket Identifiers
Subprotocol identifier
mqtt
Subprotocol generic name
mqtt
sub-protocol definition
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html
MQTT-3.1.1-CN 60
7 consistency
MQTT specification definesdefined MQTT guestclient implementation and MQTT Implemented by the serverconformance requirements
MQTT implementation cancan simultaneously be MQTT client and MQTT server.Accept inbound connectionsand establish to otherof the server's outbound connectionclothes
Server must also conformcombine MQTT guestclient and MQTT server-side requirementFind [MQTT-7.0.0-1]。
In order to with any otherConforming implementationInteroperate, aConforming implementation cannotrequired to use in this specificationAny externally definedExtensions [MQTT-
7.0.0-2]。
7.1 conformance goals
7.1.1 MQTT Server-side
a MQTT Server only satisfiesbelowAllto be considered compliant with the requirementsThis specification:
1. the server sendsof all control packetsformat must conform toChapter 2 and theformat described in Chapter 3
2. comply with the 4.7 topic match described in sectionmatching rules.
3. meet the following chaptersall in this sectionRequiredlevel requirementsrequest,clearOnly applies to the clientexcept:
- Chapter 1 – Introduction
- Chapter 2 – MQTT control message formatformula
- Chapter 3 – MQTT control packet
- Chapter 4 – operational behavior
- Chapter 6 –(if MQTT the network layer is WebSocket)
- Chapter 7 – conformance goals
Meet consistency requirementsserver'sRequiredsupport using oneone or more underlying transportTransport protocol, as long asIt provides ordered, reliable,bidirectionalbyte
stream (from client toServer and from serviceServer to client)[MQTT-7.1.1-1]. HoweverConsistency does not depend on it supportingSupport any particular
transport protocol. ServerendYessupports the 4.2 sectionany listedtransport protocol, orAny other satisfying [MQTT-7.1.1-1] requiredtransmission
protocol.
7.1.2 MQTT client
a MQTT Client only satisfiesAll of the followingOnly then is it considered conforming.This specification:
1. client sendsof all control packetsformat must conform toChapter 2 and theformat described in Chapter 3
2. meet the following chaptersall in this sectionRequiredlevel requirementsrequest,clearOnly applies to the serverexcept:
- Chapter 1 – Introduction
- Chapter 2 – MQTT control message formatformula
- Chapter 3 – MQTT control packet
- Chapter 4 – operational behavior
- Chapter 6 – (if MQTT network'snetwork layer is WebSocket)
- Chapter 7 – conformance goals
Meet consistency requirementsthe clientRequiredsupport using oneone or more underlying transportTransport protocol, as long asIt provides ordered, reliable,bidirectionalbyte
stream (from client toServer and from serviceServer to client)[MQTT-7.1.2-1]. HoweverConsistency does not depend on it supportingSupport any particular
MQTT-3.1.1-CN 61
transport protocol. ClientendYessupports the 4.2 sectionany listedtransport protocol, orAny other satisfying [MQTT-7.1.2-1] requiredtransmission
protocol.
MQTT-3.1.1-CN 62
appendix B Forceconformance specification statement(non-standardscope)
This appendix is non-normativeNormative, only asIn the body of this documentcan be foundlarge amountconformance statementThe summary is provided.Conformance requirementslimit column
Table shown in Chapter 7.
declared sequence number
specification statement
[MQTT-1.5.3-1]
UTF-8 Characters in the encoded stringcharacter dataRequiredis according to Unicode Specification [Unicode] defined and in
RFC3629 [RFC3629] medium-heavydeclared valid UTF-8 format. SpecialIt should be particularly noted that,Thesenumber
according tocannotcontains the character code at U+D800 and U+DFFF betweendata.If the server orthe Client receives
contains invalid UTF-8 CharacterControl packet,itRequiredclose the network connection。
[MQTT-1.5.3-2]
UTF-8 encoded stringcannotcontains a null character U+0000。ifclient or server receivesa packet arrived
contain U+0000 ofcontrol message,itRequiredClose the network connection.
[MQTT-1.5.3-3]
UTF-8 encoding sequence 0XEF 0xBB 0xBF totalis interpreted as U+FEFF(zero-width non-breaking spaceCharacter
character),no matterIt appears at the string'swhat position,messageRecipients cannot skip or stripleave it.
[MQTT-2.2.2-1]
Table 2.2 any marked as“retain”flag bits, all are reservedreserved for future use,Requiredset as a table
Values listed in.
[MQTT-2.2.2-2]
ifReceives an invalid flag,receiverRequiredClose the network connection.
[MQTT-2.3.1-1]
SUBSCRIBE,UNSUBSCRIBE and PUBLISH(QoS greater than 0) control packetRequiredcontains a
a non-zero 16 bitsPacket identifier (Packet Identifier。
[MQTT-2.3.1-2]
Each time the client sendsA new one of thesetype of packet whenRequiredAssign a currentlyunused packet.mark
identifier。
[MQTT-2.3.1-3]
ifA client wants to resend this particularspecial control packet, when retransmitting laterwhen that packet,itRequiredmake
Use the same identifier. When the client isafter processing the message corresponding toAfter confirmation, thisThe packet identifier is released
put reusable.QoS 1 of PUBLISH Paircorresponds to PUBACK,QoS 2 of PUBLISH corresponding
Yes PUBCOMP, and SUBSCRIBE or UNSUBSCRIBE Paircorresponding respectively are SUBACK or
UNSUBACK
[MQTT-2.3.1-4]
send a QoS 0 of PUBLISH messagewhen,sameThe conditions also apply to the serverend.
[MQTT-2.3.1-5]
QoS Set to 0 of PUBLISH messagecannotContains a packet identifier.
[MQTT-2.3.1-6]
PUBACK, PUBREC, PUBREL messageRequiredcontaining andinitially sent PUBLISH message with the same
packet identifier。
[MQTT-2.3.1-7]
and [MQTT-2.3.1-6] similar,SUBACK and UNSUBACK Requiredcontained in the corresponding
SUBSCRIBE and UNSUBSCRIBE messageThe packet identifier used incharacter.
[MQTT-3.1.0-1]
client to servernetwork connection establishmentafter establishment, the client sends tothe server's firsta messageRequiredYes
CONNECT message。
[MQTT-3.1.0-2]
on a network connectionon, the client onlycan be sent once CONNECT Message. ServerserverRequiredthe client
the second sent CONNECT message asprotocol violation handlingand disconnect the client's connection。
[MQTT-3.1.2-1]
if the protocol name is incorrectconfirm the serverYesdisconnect the clientthe connection, alsoYesaccording tosome other specificationsResume
processing CONNECT message. Forin the latter case,in accordance with this specification,Server-sidecannotcontinue processing
CONNECT message。
MQTT-3.1.1-CN 63
[MQTT-3.1.2-2]
If it is found to be unsupportedthe protocol level,Server-sideRequiredto send areturn code is 0x01(unsupported protocol
protocol level)of CONNACK messageresponse CONNECT packet,thenDisconnect the client's connection。
[MQTT-3.1.2-3]
Server-sideRequiredverify CONNECT the control packet's reservedflags (the 0 bit) is whether 0,ifNo
is 0 mustmust disconnect the client connection.
[MQTT-3.1.2-4]
If the Clean Session (CleanSession)flag is setset to 0, the serverRequiredbased oncurrent session (make
Use the client identifieridentification) stateresume with the clientcommunication. Ifnot associated with this client identifierknow
session associated with the identifier,Server-sideRequiredcreate aa new session. InAfter the connection is disconnected, when the connectionconnection disconnect
After,client and serverRequiredSavesession information.
[MQTT-3.1.2-5]
When the clean session flagis 0 session connectionafter the connection is disconnected,Server-sideRequiredthereafter QoS 1 and QoS 2
message persistence at the levelas the session statea part, ifthese messages matchwhen disconnecting, the clientclient's any
any subscription.
[MQTT-3.1.2-6]
If the Clean Session (CleanSession)flag is setset to 1, clientand the serverRequiredbefore discarding
of any session and startstart a new sessionIn other words, the session lasts only as long as the networknetwork connection equally longtime.andThis
state associated with the sessionDatacannotafter anysession reuse.
[MQTT-3.1.2.7]
Retained messages are not server-side.server session statea part of, the session terminateswhencannotdelete retained messagesmessage.
[MQTT-3.1.2-8]
Will flag (Will Flag) is setis 1, indicating ifIf the connection request isaccepted, the Will (Will
Message)MessageRequiredis stored inthe server and with this networknetwork connection association.after the network connection closes
when closed, the serverRequiredPublish this Will message, unless the serverreceived DISCONNECT when deleting a message
except for this Will messagemessage.
[MQTT-3.1.2-9]
If the Will flag isSet to 1, connectionin the connection flag Will QoS and Will Retain Fieldswill be by the server
used,at the same timein the payloadRequiredcontains Will Topic and Will Message Fields。
[MQTT-3.1.2-10]
Once published orthe server receivedsent by the client DISCONNECT packet, the Will messageJustmust
needfrom storageRemoved from the stored session state.
[MQTT-3.1.2-11]
If the Will flag isSet to 0,connectionin the flag Will QoS and Will Retain FieldsRequiredSet to
0, andin the payloadcannotcontains Will Topic and Will Message Fields。
[MQTT-3.1.2-12]
If the Will flag isSet to 0, networkwhen the network connection is disconnected,cannotsend the will message。.
[MQTT-3.1.2-13]
If the Will flag isSet to 0, leaveinstruct QoS alsoRequiredSet to 0(0x00)。
[MQTT-3.1.2-14]
If the Will flag isSet to 1, leaveinstruct QoS value ofcan equal 0(0x00),1(0x01),2(0x02)。
its valuecannotequals 3。
[MQTT-3.1.2-15]
If the Will flag isSet to 0, leavewill retain (Will Retain) flag alsoRequiredSet to 0。
[MQTT-3.1.2-16]
ifThe will retain is set to 0, the serverRequiredTreat the will message as non-retained message publishing。
[MQTT-3.1.2-17]
ifThe will retain is set to 1, the serverRequiredtreat the will message asPublished as a retained message。
[MQTT-3.1.2-18]
if the username (User Name) flag is set to 0, in the payloadcannotcontainsusername field.
[MQTT-3.1.2-19]
if the username (User Name) flag is set to 1, in the payloadRequiredcontainsusername field.
[MQTT-3.1.2-20]
if the password (Password) flagis set to 0, in the payloadcannotcontains a password field。
[MQTT-3.1.2-21]
if the password (Password) flagis set to 1, in the payloadRequiredcontains a password field
MQTT-3.1.1-CN 64
[MQTT-3.1.2-22]
If the username flagis set to 0, the password flag alsoRequiredSet to 0。
[MQTT-3.1.2-23]
The client is responsible for ensuringcontrol packet transmissionthe time interval does not exceed the keep-alivekeep-alive value.If there is no other
its control packet cancan send, the clientendRequiredsend a PINGREQ message。
[MQTT-3.1.2-24]
If the keep alivevalue is non-zero, andthe server at one and a half times thekeepalive timeno client received within
the client's control packet,itRequireddisconnect the client'snetwork connection,considernetwork connection alreadydisconnect.
[MQTT-3.1.3-1]
if included,RequiredAppear in this order: client identifierwildcard, will topic, willmessage,use
username,Password。
[MQTT-3.1.3-2]
The server uses the clientclient identifier (ClientId) knowIdentify the client. Connect to the server.the server's each clientall clients have unique
unique client identifiercharacter (ClientId). The client andthe server must bothUsage ClientId knowdistinguish between the two
between MQTT session-related state。
[MQTT-3.1.3-3]
client identifier (ClientId) RequiredExistsmoreoverRequiredYes CONNECT messageThe payload's firsta
Fields。
[MQTT-3.1.3-4]
client identifierRequiredYes 1.5.3 defined in the section UTF-8 Encoded string。
[MQTT-3.1.3-5]
Server-sideRequiredAllowed 1 to 23 bytes long UTF-8 encoded clientClient identifier, the clientclient identifier
can only contain these characterscharacter:
“0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY
Z”(uppercase letters, lowercase letters and numberscharacter).
[MQTT-3.1.3-6]
Server-sideYesallow clientclient provides a zero-bytebyte client identifieridentifier (ClientId) ,if this is done
completed,Server-sideRequiredtreat this as a special case andassign a unique clientclient identifier tothat client.but
after itRequiredassume the clientThe endpoint provides that uniqueof the client identifiercharacter,normalprocess this CONNECT
message。
[MQTT-3.1.3-7]
if the clientthe endpoint provides a zero-byteof the client identifiersymbol, itRequiredwill also clearsession flag setput
is 1。
[MQTT-3.1.3-8]
If the client providesof ClientId is zero bytesand the Clean Session flagmarked as 0, serviceendRequiredsend return code
is 0x02(Indicates the identifier is invalid) of CONNACK packet responseclient's CONNECT report
text,Then close the network connection。
[MQTT-3.1.3-9]
If the server rejectsof this ClientId,itRequiredsend returncode as 0x02(tableindicates that the identifier is invalid
format) of CONNACK reportmessage responseclient's CONNECT packet, thenclose the network connection。
[MQTT-3.1.3-10]
will topicRequiredYes 1.5.3 defined in the section UTF-8 encoded string.
[MQTT-3.1.3-11]
UsernameRequiredYes 1.5.3 defined in the section UTF-8 Encoded string。
[MQTT-3.1.4-1]
Server-sideRequiredaccording to 3.1 sectionrequirement verification CONNECT packet,ifpacket does not conform tospecification, service
does not send CONNACK reportdirect textclose the network connection。
[MQTT-3.1.4-2]
if ClientId Tableindicates the clientalready connected tothis server,then the serverRequireddisconnect reasonsome clients
connection.
[MQTT-3.1.4-3]
Server-sideRequiredaccording to 3.1.2.4 node'sdescribes performing cleanupthe session process.
[MQTT-3.1.4-4]
Server-sideRequiredsend backreturn code of zero CONNACK packet as CONNECT of the packetacknowledgment response.
[MQTT-3.1.4-5]
ifthe server rejected CONNECT, itcannothandling the client in CONNECT reportsend after the messageof
any data。
MQTT-3.1.1-CN 65
[MQTT-3.2.0-1]
the server sends CONNACK messagethe response received from the client CONNECT reportMessage. The server sends to
the client's firstmessageRequiredYes CONNACK。
[MQTT-3.2.2-1]
If the server receivesClean Session (CleanSession)Flagsis 1 ofconnection, exceptwould CONNACK
The return code in the packetSet to 0 outside, alsoRequiredwill CONNACK in the packetcurrent session setting
(Session Present)flag is 0。
[MQTT-3.2.2-2]
If the server receivesa CleanSession is 0 ofconnection, the current sessionThe value of the session flag takesdepends on the server
whether it has already saved ClientId Pairrespond to the clientthe session state.if the server has already storedsession state
state,itRequiredwill CONNACK reportthe current session flag in the packetSet to 1。
[MQTT-3.2.2-3]
ifThe server has no saved sessionstatus,itRequiredwill CONNACK in the messagethe current session's settingput
is 0. It is also necessary to CONNACK reportthe return code in the text is set to 0。
[MQTT-3.2.2-4]
If the server sendscontained a non-with a zero return code CONNACK packet,itRequiredmark the current session as
flag is set to 0。
[MQTT-3.2.2-5]
If the server sendscontained a non-with a zero return code CONNACK packet,thenitRequiredclose network
connection。.
[MQTT-3.2.2-6]
If it is considered that the above table 3.1 all connections in the above table returnthe return codes are not quite suitablesuitable,thenServer-sideRequiredclose network connection
connection, no need to send CONNACK message。
[MQTT-3.3.1-1]
client or serverrequest to resend a PUBLISH when the message,Requiredwill DUP markflag is set to 1。
[MQTT-3.3.1-2]
for QoS 0 the message,DUP FlagsRequiredSet to 0
[MQTT-3.3.1-3]
the server sends PUBLISH message to the subscriberwhen,receivedof (inbound) PUBLISH of the packet DUP
the value of the flag will not bePropagation. Send(outbound) PUBLISH message and received(inbound)
PUBLISH reportin the message DUP markflag is independentset, its valueRequiredseparatelythe basis for sending (out
station)'s PUBLISH reportwhether the messagea retransmission to determine。
[MQTT-3.3.1-4]
PUBLISH messagecannotwill QoS placesome bits are set to 1。ifthe server or the client receives QoS place
all bits are 1 of PUBLISH reportmessage, itRequiredClose networknetwork connection.
[MQTT-3.3.1-5]
If the client sends toserver's PUBLISH reporttext'sretain (RETAIN) markflag is set to 1, service
serverRequiredStore this application message and its servicequality of service level (QoS), so thatit can be distributedGive
future Topic Name matchingthe matched subscriber.
[MQTT-3.3.1-6]
a new subscription is establishedwhen established, for eachthe matching topic name, ifExistsrecentretained message, itRequired
sent to this subscriptionreader.
[MQTT-3.3.1-7]
If the server receivesa retained (RETAIN) markmarked as 1 of QoS 0 message,itRequiredbefore discarding
retained for that topicany message.itshouldthis new QoS 0 eliminatemessage as thatnew retention of a topic
retain a message, but anyat any timeYeschooses to discard it — ifThis situation occurs,thattopic will have no
has retained message。
[MQTT-3.3.1-8]
the server sends PUBLISH packet to the clientwhen, if the messageis as a clientThe result of a new subscription
send, itRequiredwill reportThe message's retain flag is set to 1。
[MQTT-3.3.1-9]
when a PUBLISH reportmessage sent tothe client is because it matches aan established subscriptionwhen subscribing, the serverRequired
Set the retain flag to 0,regardlessRetain in the message it receivedthe value of the flag isless.
MQTT-3.1.1-CN 66
[MQTT-3.3.1-10]
retained flag is 1 and a zero-byte payload PUBLISH messageWill be treated as positive by the servernormal message processing
handled, it will be sentto match the subscription topicmatching clients. In addition,under the same topicany existingstored retained
the message must be removed, so this topicany subscribers after the topicwill not receive aa retained message。
[MQTT-3.3.1-11]
Server-sidecannotstorage zerothe retained message of bytes。
[MQTT-3.3.1-12]
If the client sends toserver's PUBLISH reporttext'sRetain flag bit 0, serviceendcannotstore this message
information alsocannotRemove or replace any existing reservationsmessage.
[MQTT-3.3.2-1]
topic nameRequiredYes PUBLISH reportvariable headerThe first field of the header.itRequiredYes 1.5.3 section specifiessemantic
UTF-8 the encoded string.
[MQTT-3.3.2-2]
PUBLISH reportthe topic name in the messagecannotcontains wildcards.
[MQTT-3.3.2-3]
The server sends to the subscriberof the subscribing Client PUBLISH messagetopic nameRequiredmatchthe topic of the subscriptionFilter
(according to 4.7 matching defined in the sectionprocess).
[MQTT-3.3.4-1]
PUBLISH reportreceiver of the messageRequiredaccording toAccording to PUBLISH in the packet QoS levelsend a response, see
Table 3.4 description.
[MQTT-3.3.5-1]
Server-sideRequiredthe messageDistributed to all matching subscriptionsassigned QoS the highest-level clientend.
[MQTT-3.3.5-2]
if the server implementsdoes not authorize a certain clientclient publishes PUBLISH message, it does not haveway to notify thatclient
end.itRequiredaccording to normal QoS RulesSend a positive acknowledgmentacknowledgment, orClose the network connection.
[MQTT-3.6.1-1]
PUBREL controlcontrol packet fixed headerheader's first 3,2,1,0 bit isreserved bit,Requiredis set to 0,0,1,0. service
serverRequiredTreat any other values as notvalid and closenetwork connection.
[MQTT-3.8.1-1]
SUBSCRIBE controlcontrol message fixedthe fixed header's 3,2,1,0 bit is reservedbit,Requiredrespectively set to 0,0,1,0。
Server-sideRequiredthe otherAny value is treated asinvalid and closeclose the network connection.
[MQTT-3.8.3-1]
SUBSCRIBE reportmessage validtopic filter in the payloadListRequiredYes 1.5.3 sectiondefined UTF-8 Character
string。
[MQTT-3.8.3-2]
if the server choosesdoes not support containing wildcardswildcard topic filter,Requiredreject anywildcard-containing filterfilter
the filter's subscription request。
[MQTT-3.8.3-3]
SUBSCRIBE reportmessage'spayloadRequiredcontains at least onefor the topic filter and QoS levelfield group
matches. No payloadpayload's SUBSCRIBE messageis a violation of the protocol。
[MQTT-3-8.3-4]
if in the payloadany bit of ... is non-zero value, or QoS Not equal 0,1 or 2,Server-sideRequiredconsider
SUBSCRIBE reportmessage is notvalid and close the network connectionconnect.
[MQTT-3.8.4-1]
the server receives the clientone sent by the endpoint SUBSCRIBE when the message,RequiredUsage SUBACK packet response
response.
[MQTT-3.8.4-2]
SUBACK messageRequiredand waiting for acknowledgment SUBSCRIBE messagehave the same messagePacket Identifier.
[MQTT-3.8.4-3]
If the server receivesa SUBSCRIBE packet, packetThe topic filter and an existingsubscription's topic
the topic filter is the same,thenRequiredusing the new subscriptionsubscription completely replaces the existingstored subscriptions. The new subscription'stopic filter
filter and previously subscribedsame, but itthe maximum QoS values can be different.with this topic filtermatched by the filter
any existing retainedMessageRequiredis retransmitted,Butpublish flowcannotinterruption.
[MQTT-3.8.4-4]
If the server receivescontaining multiple topicsof the filter SUBSCRIBE packet,itRequiredas if received a
a series of multiple SUBSCRIBE messagehandle that the same way, except that it is necessary tomerge their responses into oneitems
separate SUBACK reportMessage sending.
MQTT-3.1.1-CN 67
[MQTT-3.8.4-5]
the server sends to the clientof the client SUBACK message paireach pair of topic filtersdevice and QoS waitall levelsRequiredPackage
contains a return code.this return codeRequiredindicates that the subscription is grantedthe maximum QoS level,or denotes
this subscription fails。
[MQTT-3.8.4-6]
the server may grantthan the subscriber requireslower QoS level. In response to the subscriptionthe message sent due to subscriptioninformation
of the payload QoS RequiredYesoriginal publish messageinformation QoS andgranted by the server QoS twothe smallest among
value. If the original messageinformation QoS Yes 1 and is grantedthe maximum QoS Yes 0, allowing the server to repeatsend a
a copy of the message toSubscriber.
[MQTT-3.9.3-1]
the order of return codesRequiredand SUBSCRIBE messagein the topic filterthe order of the server is the same。
[MQTT-3.9.3-2]
0x00, 0x01, 0x02, 0x80 ofexternal SUBACK return codes are reservedof,cannotuse.
[MQTT-3.10.1-1]
UNSUBSCRIBE reporttext fixedthe fixed header's 3,2,1,0 bit is to maintainReserved bit andRequiredset separatelyis
0,0,1,0. serviceserverRequiredconsider any otherthe values are all invalidand close the networkconnection.
[MQTT-3.10.3-1]
UNSUBSCRIBE reportin the textthe topic filterRequiredis continuously packed, according to 1.5.3 sectiondefined
UTF-8 encoded string.
[MQTT-3.10.3-2]
UNSUBSCRIBE reporttext'spayloadRequiredat least includecontains a messagefilter. There is noof the payload
UNSUBSCRIBE reporttext isviolating the protocol。
[MQTT-3.10.4-1]
UNSUBSCRIBE reporttext mentionprovided topic filter (regardless of whether it containswildcard)Requiredwith the server maintain
the client that has thisthe current topiccompare the filter set character by charactercomparison. If anyany filter fully matches
match,Then it (the server)its own subscription will be deleted, otherwise there will be nofurther processing。
[MQTT-3.10.4-2]
If the server deletesa subscription,itRequiredstop delivering any newmessage to thisClient.
[MQTT-3.10.4-3]
If the server deletesa subscription,itRequiredfinish delivering any alreadyalready started to clientsent to the client QoS
1 and QoS 2 of the message。
[MQTT-3.10.4-4]
Server-sideRequiredsend UNSUBACK reportmessage responseclient's UNSUBSCRIBE request.
UNSUBACK messageRequiredcontains and UNSUBSCRIBE messagethe same Packetidentifier.
[MQTT-3.10.4-5]
even ifDid not delete any topic subscriptions,Server-sidealsoRequiredsend a SUBACK response。
[MQTT-3.10.4-6]
If the server receivescontaining multiple topicsof the filter UNSUBSCRIBE packet,itRequiredas if received
a series of multiple UNSUBSCRIBE reportsame as the messageprocess that packet,except for theirmerge response into
a separate UNSUBACK messageoutside.
[MQTT-3.12.4-1]
Server-sideRequiredsend PINGRESP packet responseclient's PINGREQ message。
[MQTT-3.14.1-1]
Server-sideRequiredverify allAll reserved bits are setset to 0, ifthey are not 0 Requireddisconnectconnection.
[MQTT-3.14.4-1]
client sends DISCONNECT reportafter the message,Requiredclose networkconnection.
[MQTT-3.14.4-2]
client sends DISCONNECT reportafter the message,cannotthrough thatnetwork connection thensend any control packet
text.
[MQTT-3.14.4-3]
server receives DISCONNECT reportwhen the message,Requireddiscard any withThe unacknowledged messages associated with the current connectionthe published will
will message, specifically describingdescribed in 3.1.2.5 section.
[MQTT-4.1.0-1]
during the entire session, client and serverserver allRequiredstore session statestate.
[MQTT-4.1.0-2]
SessionRequiredLasts at least as long as its active network connectionconnect for the same durationspace.
MQTT-3.1.1-CN 68
[MQTT-4.3.1-1]
for QoS 0 ofdelivery protocol, the sendersenderRequiredsend QoS equals 0,DUP equals 0 of PUBLISH
message。
[MQTT-4.3.2-1]
for QoS 1 ofdistribution protocol,sender
each time a new application message is sentall messagesRequiredAssign an un-the packet identifier usedcharacter.
MUST send a PUBLISH Packet containing this Packet Identifier with
QoS=1, DUP=0.
sent PUBLISH messageRequiredcontains a packetidentifier and QoS equals 1,DUP equals
0。
Requiredthis PUBLISH messageregarded as
unacknowledged
,untilreceives the corresponding packet from the receiver
of PUBACK packet.4.4 byte has aone about unacknowledgeddiscussion of messages.
[MQTT-4.3.2-2]
for QoS 1 ofdelivery protocol, the receiverreceiver
response PUBACK messageRequiredcontains amessage identifiers,this identifier comes fromupon receiving
of,That has accepted ownership PUBLISH packet.
sent PUBACK reportafter the message,the receiver mustany containing the same packet identifierthe identifier's entry
station PUBLISH messageas a newthe message, and ignore its DUP Flagsthe value of.
[MQTT-4.3.3-1]
for QoS 2 ofdelivery protocol, the sendersender
must assign to the to-be-sent ...new application message distributionassign an unused packetidentifier.
MUST send a PUBLISH packet containing this Packet Identifier with
QoS=2, DUP=0.
sent PUBLISH messageRequiredcontains a packetidentifier and packetof QoS equals 2,,DUP
equals 0。
Requiredthis PUBLISH messageregarded as
unacknowledged
,untilreceives the corresponding packet from the receiver
of PUBREC packet.4.4 sectionThere is a message about unacknowledgeddiscussion of messages.
received PUBREC after the messageRequiredsend a PUBREL packet.PUBREL packet must
Contains the original PUBLISH the same message as the messagePacket Identifier.
MUST treat the PUBREL packet as “unacknowledged” until it has
received the corresponding PUBCOMP packet from the receiver.
Requiredthis PUBREL reportmessage regarded as
unacknowledged
,untilreceives the corresponding one from the receiver
PUBCOMP packet.
once the corresponding ... has been sentof PUBREL message thencannotresend this PUBLISH packet.
[MQTT-4.3.3-2]
forQoS 2delivery protocol, receiveperson
response PUBREC messageRequiredContains a packet identifier, whichthe identifier from the received packet、
alreadyaccepting ownership of PUBLISH packet.
Upon receiving the corresponding PUBREL before the message,receiverRequiredsend PUBREC reportconfirmationduty
any subsequent having the samewith the same identifier PUBLISH packet. In this casebelow, itcannotrepeat
deliver messages to anysubsequent receivers。
response PUBREL of the packet PUBCOMP messageRequiredcontaining and PUBREL reportsame as the message
identifier.
send PUBCOMP reportof the textafter, the receivermust include the sameany with the same message identifierafter
continue PUBLISH messageas a newThe publication.
MQTT-3.1.1-CN 69
[MQTT-4.4.0-1]
the client sets the Clean Start flagsession (CleanSession) markmarked as 0 reconnectwhen, the clientand the serverRequiredmake
using the original packet identifieridentifier resends anyunacknowledged PUBLISH message (if QoS>0) and
PUBREL message。
[MQTT-4.5.0-1]
The server takes over inboundownership of the application messagewhen authorized, itRequiredthe messageadd to subscriptionmatching clientof
in the session state.matchSee the rule definition 4.7 section.
[MQTT-4.5.0-2]
clientRequiredaccording to the possiblethe quality of service used (QoS) Rule confirmationany it receives PUBLISH packet,
regardlessIt chooses whether to process packets containingapplication message。
[MQTT-4.6.0-1]
Resend any previous PUBLISH reportwhen the message,Requiredaccording to original PUBLISH messageretransmit in the order of sending
(applies to QoS 1 and QoS 2 Message)。
[MQTT-4.6.0-2]
Requiredaccording to the corresponding PUBLISH Send the packets in order PUBACK reporttext (QoS 1 Message)。
[MQTT-4.6.0-3]
Requiredaccording to the corresponding PUBLISH Send the packets in order PUBREC reporttext (QoS 2 Message)。
[MQTT-4.6.0-4]
Requiredaccording to the corresponding PUBREC order of packetssequential send PUBREL message (QoS 2 Message)。
[MQTT-4.6.0-5]
Server-sideRequireddefaultFor each topic there isorder. ItYesprovide aa management function orother machine
mechanism, toAllowedOne or more topicstreated asunordered。
[MQTT-4.6.0-6]
The server handles sendingto ordered topicswhen a message,Requiredas abovethe rules will messagemessage distributed to eachsubscribe
reader.in addition, itRequiredaccording to what is received from the clientsend in the order received PUBLISH messageto the consumer (for the corresponding
the same topic and QoS)。
[MQTT-4.7.1-1]
The topic filter mayto use wildcards, but topic namescannotUsageWildcard.
[MQTT-4.7.1-2]
multi-level wildcard mustlocated in its ownlevel or following the topic levelafter the level separator. Regardless of the situation
condition,it allRequiredis the last level of the topic filtercharacters。
[MQTT-4.7.1-3]
In the topic filterany level cancan use a single-level wildcard,including thefirst and lastA level.
howeveritRequiredoccupies the entire level of the filter。
[MQTT-4.7.2-1]
Server-sidecannotwill $ Topic name match starting with charactermatch wildcard (#or+) opentopic filter at the startdevice.
[MQTT-4.7.3-1]
all topic names andTopic filterRequiredMust contain at least one character.
[MQTT-4.7.3-2]
topic name and topic filterfiltercannotcontains a null character (Unicode U+0000) [Unicode] 。
[MQTT-4.7.3-3]
topic name and topic filterfilter is UTF-8 Encoded string, theycannotExceeded 65535 byte。
[MQTT-4.7.3-4]
when matching subscriptions, the serverservercannotfor topic name orThe topic filter executesperform any normalization
(normalization)processing,Cannot modify or replace anyany unrecognized charactercharacter.
[MQTT-4.8.0-1]
Unless otherwise specified,If the server orThe client encounteredBehavior that violates the protocol,itRequireddisable transmission of this
a protocol violation controlthe network connection of the packetconnect.
[MQTT-4.8.0-2]
If the client or serverserver side processes inboundencountered a transient when processing a control packettime error,itRequiredclose the transport that
Network of control messagesconnection.
[MQTT-6.0.0-1]
MQTT control packetRequiredUsage WebSocket binary numberData frame sent. Ifreceive any otherType
Data frame, receivepersonRequiredclose the network connection。
[MQTT-6.0.0-2]
single WebSocket numberData frame can contain multipleone or part MQTT Packet. The receivercannotSuppose
MQTT Control messages according to WebSocket frame boundary alignment。
MQTT-3.1.1-CN 70
[MQTT-6.0.0-3]
clientRequiredthe characterstring mqtt contained in itprovided WebSocket sub-protocolin the protocol list.
[MQTT-6.0.0-4]
Server selects and returnsreturned WebSocket sub-protocolprotocol nameRequiredYes mqtt
[MQTT-7.0.0-1]
MQTT Implementation can simultaneously be MQTT client and MQTT Server side. Accept incomingSite connection and establishment to its
Its server-side outboundconnected servermust simultaneously satisfy MQTT client and MQTT server-side requirement
request.
[MQTT-7.0.0-2]
In order to with any otherConforming implementationInteroperate, aConforming implementation cannotrequired to use in thisoutside the specification
Any defined extension。
[MQTT-7.1.1-1]
Meet consistency requirementsserver'sRequiredsupport using oneone or more underlying transportTransport protocol, as long asit provides
ordered, canReliable, bidirectional byte stream (From client to serverServer side and from server to clientclient)
[MQTT-7.1.2-1]
Meet consistency requirementsthe clientRequiredsupport using oneone or more underlying transportTransport protocol, as long asit provides
ordered, canReliable, bidirectional byte stream (From client to serverServer side and from server to clientclient)