Turn from: www.jianshu.com/p/3d5b487c6…

I: Preface I have been learning about MQTT protocol recently, but the content is a little too much. We hereby sort out MQTT protocol and its process from the server side to the client side and record it as follows.

MQTT (Message Queuing Telemetry Transport) is an instant messaging protocol developed by IBM. MQTT is a lightweight, proxy-based publish/subscribe messaging protocol. Its protocol is simple and compact, strong scalability, provincial traffic, save electricity, advantages, and already have a PHP, JAVA, Python, C, C #, Go, and many other languages, basic can be used on any platform, almost can connect all networking items and external, so especially suitable for used as communication protocols of the Internet of things, Practical scenarios include remote sensing data, cars, smart homes, smart cities, medical care and so on.

MQTT features MQTT is a protocol designed for the communication of remote sensors and control devices with limited computing power and working on low bandwidth and unreliable networks. It has the following features:

1. Use publish/subscribe message pattern to provide one-to-many message publishing and decouple application;

2. Message transmission that shields the load content;

3. Use TCP/IP to provide network connection;

4. There are three qualities of message publishing service:

“At most once”, message publishing is entirely dependent on the underlying TCP/IP network. Message loss or duplication occurs. This level can be used for environmental sensor data where the loss of a read record does not matter because a second send will follow shortly after.

“At least once” ensures that messages arrive, but message duplication may occur.

“Only once” ensures that the message arrives once. This level can be used in cases where duplicate or missing messages result in incorrect results in a billing system.

5, small transmission, low overhead (fixed length header is 2 bytes), protocol exchange is minimized to reduce network traffic;

6. Mechanisms for notifying interested parties of client outages using Last Will and Testament features;

MQTT protocol Content 1: Message model MQTT is a broker-based publish/subscribe messaging protocol. Unlike the request/answer synchronous pattern, the publish/subscribe pattern decouples the relationship between the publishing client (publisher) and the subscribing client (subscriber), meaning that there is no direct connection between publisher and subscriber. A publisher can correspond to multiple subscribers, and when a publisher changes, it can notify all subscribers one by one. This mode provides greater network scalability and a more dynamic network topologyIn addition, using MQTT protocol, the equipment can be easily connected to the Cloud service of the Internet of Things, manage the equipment and process data, and finally apply to various business scenarios, as shown in the figure below2 Quality of Service

MQTT provides three qualities of service: at most once (qos = 0), packet loss may occur. It is used in the case of low demand for real-time performance. This level can be applied to situations such as environmental sensor data where a loss of read records does not matter because the next read record will soon be generated.

At least once (qos = 1), the packet is guaranteed to arrive at its destination, but repackets may occur.

Exactly once (qos = 2), the packet is guaranteed to arrive at the destination without repacket. This level can be used in scenarios such as billing systems where message loss or duplication may cause incorrect charges to be generated.

Quality of Service 3 Topics and wildcards

Topic names are used to identify the channel of information for published messages. Subscribers use it to make sure they receive the information they care about. It is a layered structure with a slash “/” as the separator (this is somewhat restful). Topics can also be filtered by wildcards. Where + can filter one level, and # can only appear at the end of the topic to filter any level of level. It is worth noting that MQTT allows you to subscribe to topics using wildcards, but not broadcast them using wildcards.

Here’s an example:

Building – B /floor-5: Represents equipment on the 5th floor of Building B.

+/floor-5: represents the 5th floor of any building.

Building – B /# : Represents all equipment in building B.

4 the will

When a client disconnects, it expects the client to send the message it specifies. The message has the same structure as a normal message. This is done by setting the bit and filling in the relevant information (described below).

5 Message Types

Message type Type encoding description

Reserved 0 to retain

Connect 1 Connection request from the client to the server

ConnACK 2 The response of the server to a connection request

Publish 3 Publishes the message

Puback 4 Confirms the new published message, which is QoS 1’s reply to the PUBLISH message

PubRec 5 QoS 2 The first part of a message flow, which indicates that the message has been published

PubRel 6 QoS 2 The second part of a message flow, which indicates that the message has been released

PubComp 7 The third part of the QoS 2 message flow, indicating that the message has been published

Subscribe 8 The client subscribes to a topic

SubBack 9 Confirms the SUBSCRIBE message

Unsubscribe 10 Message that the client terminates the subscription

UnsubBack 11 Confirms the UNSUBSCRIBE message

PingReq 12 heartbeat

PingResp 13 Confirm the heartbeat

Disconnect 14 The client notifies the MQTT agent before terminating the connection

15 keep reserved

The MQTT protocol header details the distribution of client publication messages to all corresponding subscribers via the server. A subscriber can subscribe to several Topic names, but a PUBLISH message can have only one Topic. Its message architecture is as follows:1 Fixed head

Fixed header, using two bytes, total 16 bits:Byte 1 Message type and flag field. The message type (4-7) is a 4-bit binary representation that can represent 16 message types.

Byte 2 The remaining length field (at least 1 to a maximum of 4 bytes) is stored in big-Endian mode.

The message types have been described previously. Here is a picture:DUP Flag (Open flag)

Ensure reliable transmission of messages. The default value is 0, which takes only one byte and indicates the first time to send messages. Cannot be used to detect messages sent repeatedly. This applies only to client or server attempts to reissue PUBLISH, PUBREL(the second part of the QoS 2 message flow, which indicates that the publication has been released), SUBSCRIBE(the client subscribes to a topic) or UNSUBSCRIBE(the client terminates the subscription) messages, The following conditions must be met: When QoS is greater than 0, the message needs to be acknowledged. In this case, the message ID must be included in the variable header. A value of 1 indicates that the current message has been sent previously.

Quality of Service (QoS)

Use two binaries to represent a PUBLISH message:

RETAIN (keep)

Only for PUBLISH messages. Different values, different meanings:

0: Push this message only for current subscribers.

1: indicates that the sent message needs to be persistent (not affected by server restart), not only to the current subscribers, and the new subscribers subscribed to this Topic name will be pushed immediately.

In addition, for newly added subscribers, only the latest RETAIN Flag = 1 message push will be retrieved.

Remaining Length

The number of bytes remaining in the current message, including the variable header and payload (more appropriately called content /body). Maximum value of a single byte: 01111111 Hexadecimal: 0x7F. The value of hexadecimal is 127. Why can’t a single byte be 11111111 (0xFF)? Because the MQTT protocol dictates that the eighth (highest) bit is 1, indicating the existence of subsequent bytes.

The MQTT protocol also allows a maximum of four bytes to represent the remaining length. Then the maximum length is: 0xFF,0xFF,0xFF,0x7F.

Binary representation is: 1, 11111111111111, 1111111, 1011111

Decimal notation: 268435455 byte=261120KB=256MB=0.25GB

The range of values between four bytes:

2 Variable head

The fixed header defines only the message type and some flag bits, some metadata of the message that needs to be put into the variable header. Variable header content byte length + Payload/ Payload byte length = remaining length. Keep this in mind. Variable headers, which contain the protocol name, version number, connection flag, user authorization, heartbeat time, etc., will be covered later.

3 Payload/ message body/Payload

The body of the message exists primarily for use with fixed/variable header commands (for example, the CONNECT variable header User name flag, if 1, requires the User name string to be appended to the body).

CONNECT the SUBSCRIBE/SUBACK/PUBLISH news have the body of the message. The body of a PUBLISH message is treated as binary.

Keep in mind that MQTT only allows custom features to be used in the body of PUBLISH messages, not in the fixed/variable headers. This is also in order to keep the protocol from becoming a formality, becoming very fragmented and accommodating existing clients and so on. For example, if you support compression, you can define data support in Payload and read it in your application

4 Message IDENTIFIER/MESSAGE ID

A 16-bit unsigned bit value of short (the value 0,0 cannot be reserved as an invalid message ID) must only be unique in a communication message sent from the server to the client in one direction and from the client to the server in the other direction. For example, when a client sends a message to a server, it is possible for the server to send a message to a client, but it does not matter.

In a variable header, the order in which two bytes are required is MSB(Most Significant Bit) LSB(Last/Least Significant Bit). The most significant bit is to the left/above the least significant bit, indicating that this is a big-endian/network byte order, which is in line with human reading habits, with the most significant bit at the far left.

MQTT protocol connection and heartbeat Introduction to CONNECT

After the TCP connection is established, the Client sends a Request to the Server.

If no Response is received from the Server within a period of time, the socket is closed and a session connection is established again.

If a ClientID is already connected to the server, an old connection holding the same ClientID must be closed by the server before a new one can be established. Here is a more complete CONNECT message structure:

The parameters related to Connect Flags are described below

1 Connect Flags

One byte means that the other seven bits have different meanings except for the first bit, which is reserved. This is important for business and has a significant impact on the overall flow of messages to keep in mind.

2 Clean Session

0 indicates that if the subscribed client disconnects, it should be saved as the message to be pushed (QoS is 1 and QoS is 2). When the subscribed client reconnects, it should push these messages (if the client is disconnected for a long time, an expiration value should be set). 1. Disconnection server will clean up related information, reconnect, and subscribe again.

3 Will Flag

Defines the actions that the server needs to take if the client (which does not actively send DISCONNECT message) is disconnected due to a network exception.

In short, it is the client’s pre-defined Last Will, also known as a Testament, to be left in the event of an unexpected disconnect. This will is a subject and corresponding message predefined by the client, attached to the variable header of CONNECT, which the server actively publishes in the event of an exception to the client connection.

Will Qos and Will Retain are read only when the Will Flag bit is 1. In this case, Will Topic and Will Message contents must be displayed in the Message body payload. Otherwise, Will Qos and Will Retain values are ignored.

4 Will Qos

The value is the same as the QoS level of the fixed header of the PUBLISH message. It will be clearer to skip this and come back to the PUBLISH message. If the value of Will Flag is 1, the Will QoS takes effect. Otherwise, it is ignored.

5 Will Retain

If the Will Flag is set, the Will Retain Flag is valid, otherwise it is ignored. Whether the server should continue to save after the client accidentally disconnects from the server and publishes its Will Message. This property has the same meaning as the RETAIN flag in the PUBLISH fixed header and is skipped here.

6 User Name and Password Flag

For authorization, both are either 0 or 1, otherwise both are invalid. Both values are 0, indicating that clients can freely connect/subscribe, and both values are 1, indicating that connections/subscriptions require authorization.

CONNACK

After receiving the CONNECT message, the server should return a CONNACK message in response:

If the client bypasses the CONNECT message and sends another type of message directly, the server should close the illegal connection. If the client does not receive CONNACT after sending the CONNECT message, it needs to close the current connection and reconnect

The same Client ID indicates that the Client is connected to the server. The server can complete the connection only after the previous Client is disconnected. The Client sends an invalid CONNECT message and the server needs to be shut down.

A complete CONNACK message looks like this:

PUBLISH PUBLISH message

Both clients and Servier can PUBLISH. (Server refers to MQTT’s middleware services, such as Apollo, Mosquitto, etc.)

The Publish message should contain a TopicName(Subject/Channel), or subscribe keyword.

The specific interaction is clearly depicted in the following diagram:

PUBACK’s confirmation after the announcement

When QoS is 1, the Server sends the confirmation to the Client (the Client deletes the confirmation after receiving the confirmation), and the subscriber sends the confirmation to the Server. PUBREC / PUBREL / PUBCOMP

QoS = 2

  1. Server->Client publishes PUBREC (received);

  2. Client->Server releases PUBREL

  3. Server->Client publishes PUBCOMP (completed), Client deletes MSG; Subscribers also issue similar process confirmations to the Server.

PUBREC literally stands for Assured Publish Received, as a subscriber/server response to the sender of a published publish message with QoS level = 2, confirming receipt as the second message in the QoS level = 2 message flow. Compared to PUBACK, everything is the same except the message type.

PUBREL third message of a protocol flow whose Qos level is 2. The publisher of a PUBLISH message sends it and the participant receives it. The complete demonstration is as follows

PUBCOMP, as the fourth and final message in the QoS Level = 2 message flow, is a response message from one party receiving PUBREL to the other party. Complete message overview, same as PUBREL, except message type.

PINGREQ/PINGRES Indicates the heartbeat

The Client is responsible for sending the KeepAliveTime duration to the Server (indicating that the Client is currently active). Within a period of time, PINGREQ is sent, and the Server sends PINGRES confirmation.

If the Server does not receive a PINGREQ within 1.5 hours, it disconnects.

The Client does not receive PINGRES within one period and is disconnected. Procedure

Typically, the duration is set to a few minutes. A maximum of 18 hours. 0 indicates that the connection has not been disconnected.

Keep Alive timer

Defines, in seconds, the maximum interval for the server to receive messages from the client. Generally, application services check whether the client network is connected at the service level, rather than the TCP/IP heartbeat mechanism (for example, the SO_KEEPALIVE option of sockets is enabled). Typically, within a heartbeat interval, the client sends a PINGREQ message to the server, which returns a PINGRESP message, completes one heartbeat interaction, and waits for the next. If the client does not receive heartbeat feedback, the TCP/IP port connection is closed and the client goes offline. 16-bit two bytes, which can be considered an unsigned short value. Maximum value, 2^16-1 = 65535 seconds = 18 hours. The minimum value can be 0, indicating that the client is continuously started. Generally set to a few minutes, such as micro confidence jump period of 300 seconds

Notification mechanism of abnormal connection interruption

The CONNECT message, once set with the Will flag in the variable header, enables the last-will-and-Testament feature, which is great.

In the event of an abnormal client outage, the server Will be triggered to publish a Will Message to the Will Topic Topic, notifying the Will Topic subscriber that the client has quit due to an abnormal interruption.

Packet capture and analysis header data

Wireshark is used to capture MQTT protocol data. Wireshark is used to capture MQTT protocol data. Wireshark is used to capture MQTT protocol data

While I’m using Wireshark + Paho (GUI) here, Borker is using Mosquitos. By the way, PAho is a sub-project under Eclipse, it is only a library, the official website does not seem to provide the GUI version (graphical interface), I am here from github source code compiled to get the interface version, this interface for MQTT message debugging is quite easy to use, if you are interested can also try. Github address of the project: github.com/eclipse/pah…

The latest version of Wireshark supports MQTT, so you can filter MQTT requests by entering MQTT in the filter

As you can see in the figure above, I have already caught my request to establish a connection in paHO, and the connect Command can be clearly seen in the info column. Let’s look at the specific packet below, which shows the original hexadecimal. 10 1E 00 04 4D 51 54 54 04 02 00 3C 00 12 70 61 68 6f 31 31 31 35 37 37 32 31 39 34 33 36 30 33

Let’s analyze the packet. The first two bytes are 10 and 1e

The first byte 0x10 corresponds to the base 2 of 10000, which is displayed in 8 bits (0001, 0000)

Second byte: 0x1e represents the remaining length, that is, the total number of bytes after the second byte in the request packet, 0x1e in decimal form is 1*16+14=30 bytes, “00 04 4D 51 54 54 04 02 00 3C 00 12 70 61 68 6F 31 31 31 31 35 37 37 32 31 39 34 33 36 30 33”

Variable head, again put the picture as follows:

Three: MQTT server (middleware implementing MQTT protocol) MQTT protocol server: github.com/mqtt/mqtt.g…

MQTT Protocol Library (Client) : github.com/mqtt/mqtt.g…

Official website of MQTT protocol: mqtt.org/

There are many open source brokers available for the MQTT protocol, and I’ve compiled two here, Apollo and Mosquito; Detailed server selection can be found in the server link above. The environment configuration and server setup described below are all on the MAC environment. For other platforms, refer to the detailed documentation for selecting brokers.

Apollo-broker setup

Apache Apollo is a proxy server based on ActiveMQ that supports multiple protocols such as STOMP, AMQP, MQTT, SSL, etc. Its construction process is as follows:

1 configure JAVA_HOME. Apollo is written in Java, so you need a Java environment to build Apollo-broker. How to configure JAVA_HOME in MAC?

2 download the Apollo,

Here I choose OS X version for my macbook

Unzip the downloaded files to the appropriate directory (preferably a separate one for subsequent sorting). The apache-Apollo-xxx folder defaults to the environment variable ${APOLLO_HOME};

There are two ways to create a broker

CD places broker paths (it is recommended to place them in the folder created in 2 for later viewing or organizing)

${APOLLO_HOME}/bin/ Apollo create MyBroker //

Create XXX /bin/ Apollo create MyBroker# Generate an MQTT_test directory in the current directory, which contains: MyBroker Generating ssl keystore… You can now start the broker by executing:”/Users/ LQX /Desktop/ unnamed folder /MyBroker/bin/ Apollo-broker “run Or You can run the Brokerinthe background using: “/ Users/LQX/Desktop/unnamed folders/MyBroker/bin/Apollo – broker – service” start

The successful file directory should look something like this:

Bin Running scripts

Etc Environment Configuration

Data stores persistent data

Log Run logs

TMP temporary files

4 run broker

CD MyBroker(folder created in 3)

apollo-broker run

Since Apollo provides a visual Web interface (which is why I chose him), we type in the browser

http://127.0.0.1:61680/ (HTTP access) or https://127.0.0.1:61681/ (HTTPS access, available for research MQTT + SSL) Enter username and password to log in (default username: admin password: password)

I’ll cover server-client mediation in the client section.

It is worth noting that the default TCP port is 61613. When I wrote the demo before, the client could not connect to the broker, because the port number of the host where the server is located was 61613. Therefore, you must check whether the corresponding port is open after setting up the server

For Mac ports again, current versions of OSX prior to 10.10 can open ports with the following instructions

Sudo ipfw add 61613 allow TCP from any to any dst-port 61613;

Osx10.10 after the current version has not found the method to open the port, if you know, can tell me, consult the information obtained processing mode is to use Nginx server to do port forwarding, but it is troublesome, so I used a simple method to replace, the method is as follows:

The default TCP port on the Mac is 1883, which you can see in networking utilities, so we need to go to the Apollobroker configuration file and change tcpport from 61613 to 1883.

Locate apollo.xml in the broker folder you created above. This is the configuration file

Change the TCP configuration port to 1883

Then restart the service. Other systems can directly open port number 61613, convenient and fast.

Apollo provides a test page in addition to a visual Web interface,

Open the page as follows

After connecting, you can go to the Apollo monitoring page (http://127.0.0.1:61680/ (HTTP access) or https://127.0.0.1:61681/ (HTTPS access, available for research MQTT + SSL)) and find the topics and consumers you are connecting to.

At this point, apollo-related servers need to be covered.

Ii: Mosquito server setup

Mosquitos is mosquitos open source messaging broker software that implements MQTT V3.1 and provides mosquitos with a lightweight, publish/subscribe push mode that makes device-to-device short messaging easy to use

Mosquitto is C language implementation, don’t need to configure the environment, we directly use homebrew installation, simple and quick.

1 Open the terminal and type Brew Install mosquitto to install directly

Linux(Ubuntu) installation is also relatively easy (note #, root permission required) :

apt install mosquitto

Of course, if it is really so installed, so sorry, the installed version may be relatively low, but it does not matter, still can use. But if you want to install the latest version, follow these commands:

Mosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquitmosquito

apt-get –purge remove mosquitto

Mosquito warehouse and update

# apt-add-repository ppa:mosquitto-dev/mosquitto-ppa

apt-get update

3. Installation mosquitos

# apt-get install mosquitto

4. Check whether the installation is successful

# service mosquitto status

The following page is displayed when the installation is successful

Mosquito-service startup order

Brew Services stop mosquito

Brew Services start mosquitos

Brew Services Restart mosquitto

Then tell me the configuration files of the mosquito, the configuration file is a directory/usr/local/etc/mosquitto/mosquitto. Under the conf file. The configuration file is described as follows:

# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

# General configuration    

# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

The interval between client heartbeats

#retry_interval 20    

The refresh time of system status

#sys_interval 10    

The value 0 indicates the recovery time of system resources

#store_clean_interval 10    

PID of the server process

#pid_file /var/run/mosquitto.pid    

System user of the server process

#user mosquitto    

# Maximum number of concurrent client heartbeat messages

#max_inflight_messages 10    

Client heartbeat message cache queue

#max_queued_messages 100    

This parameter is used to set the client long connection expiration time. By default, it never expires

#persistent_client_expiration    

# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

# Default listener    

# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

IP address of the service binding

#bind_address    

The port number of the service binding

#port 1883    

# Maximum number of connections allowed. -1 indicates no limit

#max_connections -1    

# cafile: indicates the CA certificate file

# capath: indicates the CA certificate directory

# certfile: PEM certificate file

# keyfile: PEM keyfile

#cafile    

#capath    

#certfile    

#keyfile    

A certificate must be provided to ensure data security

#require_certificate false    

# If require_certificate is true, use_identity_as_username must also be true

#use_identity_as_username false    

# enable PSK (pre-shared-key) support

#psk_hint    

The SSL/TSL encryption algorithm can be obtained by running the “openssl ciphers” command

# as the output of that command.    

#ciphers    

# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

# Persistence    

# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

# The interval between messages being automatically saved

#autosave_interval 1800    

# Switch of message autosave function

#autosave_on_changes false    

# Persistence on/off

persistencetrue    

Persist DB files

#persistence_file mosquitto.db    

Persist DB file directories

#persistence_location /var/lib/mosquitto/    

# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

# Logging    

# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

# 4 logging modes: STdout, STderr, Syslog, topic

# None indicates no logging, which improves performance a bit

log_dest none    

# select log level (optional)

#log_type error    

#log_type warning    

#log_type notice    

#log_type information    

Whether to record client connection information

#connection_messages true    

Whether to record the log time

#log_timestamp true    

# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

# Security    

# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

The prefix limit of the client ID can be used to ensure security

#clientid_prefixes    

# allow anonymous users

#allow_anonymous true    

# username/password file, default format: username:password

#password_file    

# PSK format password file, default format: identity:key

#psk_file    

# pattern write sensor/%u/data    

ACL permission configuration:

# user restriction: user

Topic # restrictions: topic [read | write]

Pattern write sensor/%u/data

#acl_file    

# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

# Bridges    

# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

Enable “bridge” mode between services (for distributed deployment)

#connection     

#address [:]    

#topic  [[[out | in | both] qos-level] local-prefix remote-prefix]    

Set the client ID for the bridge

#clientid    

Whether to clear messages from the remote server when the bridge is disconnected

#cleansession false    

Whether to publish the status of the bridge

#notifications true    

# Set the topic address to which messages will be posted in bridge mode

# $SYS/broker/connection//state    

#notification_topic    

# set the keepalive value for the bridge

#keepalive_interval 60    

Bridge mode: automatic, lazy, once

#start_type automatic    

Automatic bridge mode timeout

#restart_timeout 30    

Bridge mode lazy timeout

#idle_timeout 60    

# Bridge client user name

#username    

# Bridge client password

#password    

# bridge_cafile: CA certificate file of the bridge client

# bridge_capath: CA certificate directory of the bridge client

# bridge_certfile: PEM certificate file of the bridge client

# bridge_keyfile: PEM keyfile for the bridge client

#bridge_cafile    

#bridge_capath    

#bridge_certfile    

#bridge_keyfile    

Mosquito configuration user name and password can refer to www.jianshu.com/p/4b545332b…

We need to change very little configuration

Just set the host and port. After the configuration is complete, restart the service to take effect.

The same thing to watch out for with Apollo is whether the port number is open or occupied.

Since Mosquito doesn’t provide a visual interface, we could test the Mosquito server with two clients subscribed to the same topic without building our own. Mosquito is basically ok at this point.

Four MQTT client client generally two commonly used MQTT tripartite library MQTTKit and MQTTClient, MQTTClient in Ios10 after the update of a version, often maintained; MQTTKit, which seems to have not been updated for a long time, so we choose MQTTClient to build the environment as iOS.

1 installation MQTTClient

Integrate pod ‘MQTTClient’ directly with Cocopod

2 related classes

3 Specific Usage

To connect here, you need to have your service open, either mosquito or Apollo

With Apollo, you need a username and password, which are admin and password by default; with Mosquito, you don’t. Host is the IP of your server, port is the port set for you. It is 1883 on my side. The host where the server is located and the mobile phone can be connected in the same LAN. Once connected, clients that subscribe to the same topic can communicate with each other, such as the webDemo provided by the Mobile client on the Apollo server.

The client receives the message

The client sends the message

Other multi-topic subscriptions or Lastwill Settings or retain Settings refer to MQTTClient’s comments.

Release resources when you’re done

At this point, a simple MQTT protocol from the server to the client to achieve this is complete, welcome to complement and improve.

Author: xia not language link: www.jianshu.com/p/3d5b487c6… The copyright of the book belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.