There are two main ways of receiving messages using the API. Applications can either call the receive
function or set the messageArrived
The receive and yield functions are intended to be used in applications without multiple threads. The messageArrived
callback function must not be set; otherwise, a background thread is started to deliver incoming publications to that callback, and receive
is not allowed.
The connect options include the MQTT keep alive timeout interval, in seconds. The server disconnects a client if no MQTT packets are received within any period of time greater than this interval. In practice, servers allow a grace period, but do not rely on this periodt. A single-threaded client must call the receive (or yield) function often enough to prevent the keep alive timeout interval from expiring. This occurs because it is the only chance the API has to send and receive MQTT packets, including acknowledgment packets for publish calls (at QoS 1 or 2).
The yield function is provided to allow a call to be made to the API within the keep alive interval without the application having to handle a received message. The keep alive interval could be set to a large value to eliminate the need for frequent calls to receive or yield. The disadvantage is that it takes longer for the server to notice when a client connection is broken. A common value to use for the keep alive interval is 60 seconds.
Setting a message arrived callback function means that a separate thread is started when the client successfully connects and stopped when the client disconnects. This background thread processes all MQTT packets and other requirements such as keeping the connection alive. The thread calls the message arrived callback function to deliver any publications received. Calling receive or yield is an error if a callback has been set.
Parent topic: Using the MQTT C Client: XPD622