MQTT protocol Précis-writers

Source: Internet
Author: User
Tags keep alive

first, the definition mqtt-mq Telemetry Transport
    • A lightweight machine-to-machine communication protocol.
    • Publish/subscribe mode.
    • Based on TCP/IP.
    • Support QoS.
    • Suitable for low bandwidth, unreliable connections, embedded devices, CPU memory resource tight.
    • is a relatively good Android message push scheme.
    • The Facebookmessenger employs Mqtt.
    • Mqtt is likely to be an important protocol for the Internet of things.

MQTT is a lightweight agent-based publish/Subscribe Message Transfer Protocol that can connect to remote devices through very little code and bandwidth. For example, through satellite and proxy connections, through dial-up and healthcare provider connectivity, as well as on some automation or small devices, and because of the small, power-saving, low protocol overhead and efficient Shang and multiple receivers to transmit information, it is also applicable to the application of the weighing device.

I believe that in order to study this agreement must be rushed to solve a problem, the above gives the applicable scene, I want to learn and understand this agreement, for the following reasons:

1, can achieve mobile message push (push)

2, the protocol is simple, the smallest head only 2 bytes, especially suitable for embedded.

3. This is an excellent example of understanding what a protocol is. Compared to other complex protocols such as the TCP,HTTP protocol, at least the documentation is read.

Here, I take the push as an example to illustrate, although now ready-made push solution is relatively mature, but this repeat reinvent the Whell still want to do, what is take doctrine, and porter what is the difference.

Second, the initial solution of the agreement

Let's talk about the structure of the whole protocol, the whole agreement can be split into:

Fixed head + variable head + message body

The Protocol is a convention on the communication between the two sides, such as passing a stream of characters, what the 1th byte means, and what the 2nd byte means .... a convention.

So the structure of the fixed head is as follows:

1, MessageTypeMessageType (0 and 15 reserved, a total of 4 bytes)
Public $operations =array (         "mqtt_connect" =>1,//request connection         "Mqtt_connack" =>2,//request answer         "mqtt_publish" = >3,//release Message         "Mqtt_puback" =>4,//release answer         "Mqtt_pubrec" =>5,//release received, guaranteed delivery 1         "Mqtt_pubrel" =>6,// Release release, guaranteed delivery 2         "Mqtt_pubcomp" =>7,//release complete, guaranteed delivery 3         "Mqtt_subscribe" =>8,//subscription request         "Mqtt_suback" =>9,// Subscription answer         "Mqtt_unsubscribe" =>10,//unsubscribe         "Mqtt_unsuback" =>11,//unsubscribe answer         "Mqtt_pingreq" =>12,// Ping request         "MQTT_PINGRESP" =>13,//ping response         "Mqtt_disconnect" =>14//disconnect        
CONNECTAfter the TCP connection is established, the client issues a request to the server. If the server's response is not received for a period of time, close the socket and reestablish a session connection. If a clientid is already connected to the server, the old connection that holds the same clientid must be closed by the server before the new build can be established. CONNACKThe server issues a response response. 0x00 Connection Accepted
0x01 Connection refused:unacceptable Protocol version
0x02 Connection Refused:identifier rejected
0x03 Connection refused:server Unavailable
0x04 Connection Refused:bad user name or password
0x05 Connection Refused:not Authorized PUBLISH Publishing MessagesClient/servier can be publish. The publish message should contain a topicname (Subject/channel), which is a subscription keyword. About topic wildcards/: Used to represent hierarchies, such as A/B,A/B/C. #: Indicates matching >=0 levels, such as A/#就匹配a/,a/b,a/b/c. A single # represents a match for all. a# and a/#/c are not allowed. +: Indicates matching a hierarchy, such as a/+ matching a/b,a/c, mismatch a/b/c. A single + is allowed, A + is not allowed, a/+/b does not allow Puback Confirmation after publishing a messageWhen Qos=1, the server publishes the acknowledgement to the client (the client receives confirmation and deletes it), and the Subscriber publishes the acknowledgement to the server. Pubrec/pubrel/pubcompqos=2 time 1. Server->client released Pubrec (received); 2. Client->server released Pubrel (released); 3. Server->client release Pubcomp (completed), client deletes MSG, and subscribers will issue similar process acknowledgments to the server. pingreq/pingres HeartbeatThe client is responsible for sending KeepAliveTime to the server. Within a length of time, send pingreq,server send pingres acknowledgment. The server disconnects without receiving pingreq within 1.5 hours. The client has not received pingres within 1 hours and is disconnected. In general, the duration is set to several minutes.  The maximum 18hours,0 indicates that it has not been disconnected. 2. DUP Flag

It is used to ensure that the message transmission is reliable, if set to 1, in the following variable length of the head more MessageID, and need to reply to confirm, to ensure that the message transmission is complete, but not to detect the message repeated send.

3. QoSUsed primarily for publish (release state) messages, guaranteeing the number of times a message is delivered. 11 Reserved after use Qos=0: at most once, it is possible to repeat or lose. Qos=1: At least once, it is possible to repeat. client[qos=1,dup=0/* repetitions */,messageid=x]--->PUBLISH--> server received, store message, publish, delete, Send back to client pubackclient receive Puback, delete message, if not received Puback, set dup++, Resend, server side re-publish, so it is possible to repeat the message.  qos=2: Only once, make sure the message arrives only once (for a more stringent billing system). 4, Retain

Used primarily for publish (release state) messages, indicating that the server wants to keep this push, and if a new subscriber appears, push the message to it. If it is not set then push to the current subscription is released.

5, fixed the head of byte 2

It is used to save the total size of the variable-length head + message body that continues.

But not directly saved, but also extensible, the mechanism is that the first 7 bits are used to save the length, the latter one for identification.

I give an example, that is, if the following size is calculated as 0<length<=127, the normal save

If it is 127<length<16383, it requires two bytes to be saved, the first byte will be the largest one position 1, indicating that it is not finished. Then the second byte continues to exist.

Take 130来 said, the first byte to save 10000011, the second byte to save 000000001, that is, 0x83,0x01, two bytes to see, the second byte weight from 2 8 times to start.

You can add a 3rd byte, up to the 4th byte. Therefore, the MQTT protocol can achieve up to 268 435 455 (0xFF, 0xFF, 0xFF, 0x7F) will be nearly 256M of data. Can be stretched and shrunk.

Variable Head

This is the full picture of the variable head.

1, first of the top 8 bytes is protocol name (encoded name), UTF encoded character "MQISDP", the first two is the encoding name of the length of 6.

Here are some more, the next protocol is the combination of this way, that is, the first two bytes represents the length of the following part, followed by the content. Here the first two bytes are 6, followed by 6 characters "MQISDP".

2, Protocol version, the protocol revision number, V3 is also fixed.

3, connect flag, connection logo, a bit like fixed head. The 8 digits represent different symbols. A 1th byte is reserved.

Clean Session,will Flag,will Qos, will retain is relative to the connect message.

Clean Session:0 indicates that if the subscribed client is disconnected, the message to be pushed is saved, and if it is reconnected, the message is pushed.

1 means elimination, which indicates that the client is the first connection, the message so the previous connection information.

Will Flag, which indicates that if the client is not sending a disconnect message interrupt, such as an IO error, is set to 1, which requires retransmission. And the next and Willqos and Willretain also to set, the message body of topic and MessageID also to set, that is to say that an error occurred, to be re-transmitted.

Will Qos, which is set at connect under normal conditions, is typically identified if Willflag is identified.

Will RETAIN: Also in Connect, if the Willflag is identified, the bits must also be identified

Usename flag and Passwordflag, used to identify whether the user and password are passed in the body of the message, only the user name and password in the body of the message are valid, and it is not lawful to mark the password without marking the user name.

4, Keep Alive, indicating the response time, if the connection or send operation is not completed, then disconnect the TCP connection, which means offline.

5, connect return Code is usually in the Connack message, indicating the connection condition returned, I can verify the connection situation.

6, Topic Name, subscribe to Message ID, MQTT is based on subscription/publish message, then this is the identity of the message subscription, like the news client in the subscription of different columns. The push category used to differentiate messages.

Mainly used in publish and subscribe. The maximum support is 32,767 characters, or 4 bytes.

Message body (PayLoad)

There are only 3 messages with the message body connect,subscribe,suback

CONNECT is primarily the client's ClientID, the subscribed topic and message, and the user name and password, which are corresponding to the would in the variable-length header.

SUBSCRIBE is a series of topics to subscribe to and QoS.

SUBACK uses the server to confirm and reply to the subject and QoS requested by subscribe.

The PUBLISH is the message body that saves the push message in binary form, of course, where the edits can be customized.

7. Message Identifier

Included in PUBLISH, Puback, Pubrec, Pubrel, Pubcomp, SUBSCRIBE, SUBACK, unsubscribe , Unsuback.

It is a 16-bit character that is used to identify the message at QoS 1 or 2 o'clock, guaranteeing the reliability of the message transmission.

As for the specific message example, we are slowly reflected in the following code.

Clean SessionIf False (flag=0), after the client disconnects, the server should save the client's subscription information. If True (flag=1), indicates that the server should discard any session state information immediately. III. The environment required:

1, Php+apache or Nginx

2, the installation of open source Agent Mosquitto, which is used as a proxy server, responsible for connection and distribution.

Installation method is very simple, http://mosquitto.org/files/binary is compiled, source is the source code installation required (make & make Install on line)

The only thing to configure is the CONFIG.MK after the decompression, after the installation of the setup file is mosquitto.conf

Of course, the main is to set whether to support SSL, there is the config.mk the bottom of the installation location settings. Everything here by default.

The default boot is the bound IP is the local IP, the port is 1883 can be set in mosquitto.conf (to remove the previous # Word comment), Linux-C can specify the settings file and run

For example: Mosquitto-c/etc/mosquitto.conf

MQTT protocol Précis-writers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.