MQTT Keep Alive
MQTT includes a keep alive function which allows to evaluate if the connection is still open.
Keep alive ensures that the connection between the broker and the client is always open and that the broker and the client is aware of being connected. When the client establishes a connection with the broker, the client communicates a time interval in seconds to the broker. This interval defines the maximum duration that broker and client cannot communicate with each other.
Messages are not required, as long as they are often interchangeable and beyond the keep-alive interval to send an additional message to confirm that the connection is still open.
If the client does not send a message during the keep-alive period, it must send a PINGREQ packet to the broker to confirm that it is available and to ensure that the broker is also still available.
The broker must disconnect a client who does not send a PINGREQ message or packet in one and a half years times the life support interval. Similarly, the client must close the connection if it does not receive a broker’s response within a reasonable time.
Let’s take a closer look at the keep alive messages. The keep alive feature uses two packet:
The PINGREQ is sent by the client and tells the broker that the client is still alive. The PINGREQ packet does
not contain payload.
When the broker receives a PINGREQ packet, the broker must respond with a PINGRESP packet to show the client that it is still available. The PINGRESP packet also contains no payload.
Typically, a disconnected client tries to reconnect. Sometimes the broker still has a half-open connection for the client. In MQTT, if the broker detects a half-open connection, it performs a “client takeover”. The broker closes the previous connection to the same client (determined by the client’s id), and establishes a new connection with the client. This behavior ensures that the half-open connection does not stop the disconnected client to reestablish a connection.
Also Read: Introduction of MQTT