- Message Queue Telemetry Transport Protocol (MQTT)
- Fundamental Features of MQTT | Set 1
- Fundamental Features of MQTT | Set 2
- Fundamental Features of MQTT | Set 3
Keep-Alive Messages :
In MQTT, when clients and brokers are communicating with each other, then connection established between two can be lost due to various reasons like –
- One of them crashed due to software errors.
- One of them crashed due to hardware errors.
Due to such software or hardware failures, two components might go out of sync. Such connections are called half-open connections. Hence to check whether connection between clients and broker is still maintained, PINGREQ and PINGRESP can be exchanged between them after specific intervals of time. This message exchange helps to check whether connection between two is still open or not.
The period of time with which these messages are exchanged is called keep-alive period.
So when client publishes message with keep-alive timer to broker, this timer indicates maximum amount of time for which client and broker can remain connected even when no message transmission is being carried out.
Only afte keep-alive timer is expired then new PINGREQ will be sent by the client to broker. PINGRESP will be sent in response by broker and keep-alive timer will be restarted (reset to 0). This message communication will help to ensure that two components are still connected. PINGREQ and PINGRESP messages have no payload. The following two factors have to be taken into consideration for Keep-alive messages –
- If no PINGRESP is received by client, it should close connection.
- If no PINGREQ is received from client within 1.5 times of keep-alive timer, broker should close connection.
In the above program, client with ID: 1 connects with broker with keep-alive timer of 5 seconds. Hence, PINGREQ and PINGRESP will be exchanged between publisher client (ID:1) and broker after every 5 seconds.
On the other hand, publisher’s client will publish messages every 10 seconds to broker. The broker will receive PUBLISH from client id 1 and send an acknowledgment back as Qos level used is 1. The broker will also send PUBLISH to subscriber client 2, which will thus receive published messages after every 10 seconds.
If the publisher client publishes no messages, then after every 5 seconds, only PINGREQ and PINGRESP will be exchanged. Here if subscriber client also specifies keep-alive period, then these PING messages will be exchanged by broker with both clients having IDs 1 and 2 respectively.