Introduction
When the client disconnects, a will message sent to the relevant subscriber. Will Message will be sent in the following cases:
An I/O error occurred on the server or the network failed;
The client loses contact during the defined heartbeat period;
The client closes the network connection before sending the offline packet;
The server closes the network connection before receiving the offline packet.
The will message is usually specified when the client CONNECT is used. As shown below, when connecting, it is set by calling the setWill method of the MqttConnectOptions instance. Any client who subscribes to the topic below can receive the will message.
//Method 1 (MqttTopic topic, byte[]payload, int qos, boolean retained)
//Method 2 (.String topic, byte[] payload, int qos, boolean retained)
Use scenarios
When client A connects, the will message is set to "offline", and client B subscribes to this will topic. When AabnormalWhen disconnected, client B will receive this "offline" will message, thus knowing that client A is offline.
Connect Flag message field
The will message will not be sent after the client calls the disconnect method normally.
Will Flag Function In short, it is the last wish left by the client when it is abnormally disconnected, also known as a testament. This will is a topic and corresponding message predefined by the client, attached to the variable message header of CONNECT. If an exception occurs in the client connection, the server will actively publish this message.
When the Will Flag bit is 1, Will QoS and Will Retain will be read. At this time, the specific contents of Will Topic and Will Message will appear in the message body, otherwise the Will QoS and Will Retain values will be ignored.
When the Will Flag bit is 0, Will Qos and Will Retain are invalid.
Command line example
Here is an example of Will Message:
clientid=sub predefined will message:
mosquitto_sub --will-topic test --will-payload die --will-qos 2 -t topic -i sub -h 192.168.1.1
2. Client clientid=alive at 192.168.1.1 (EMQServer) Subscribe to the Will Topic
mosquitto_sub -t test -i alive -q 2 -h 192.168.1.1
3. Disconnect the Sub end abnormally andServerThe Pub side receives Will Message.
Advanced usage scenarios Here we introduce how to use Retained messages and Will messages.
Client A will message is set to "offline", and the will theme is set to the same A/status;
When client A connects, a Retained message of "online" is sent to topic A/status. When other clients subscribe to topic A/status, the Retained message is "online"; when client A is abnormally disconnected, the system automatically sends a "offline" message to topic A/status. Other clients subscribed to this topic will receive a "offline" message immediately; if the will message is set to Retained, when a new client subscribed to the A/status topic is online, the message obtained is "offline".