There are two main ways of receiving messages using the API. Applications may 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 will be started to deliver incoming publications to that callback, and receive
will not be allowed.
The connect options include the MQTT keep alive timeout interval, in seconds. The server will disconnect a client if no MQTT packets are received within any period of time greater than this. In practice, servers will allow a grace period as well, but this should not be relied upon by the client. The consequence of this is that a single-threaded client must call the receive (or yield) function often enough to prevent the keep alive timeout interval from expiring. This is because it is the only chance the API has to send and receive MQTT packets, including acknowledgement 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 will take 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 will be started when the client successfully connects and stopped when the client disconnects. This background thread will process all MQTT packets and other requirements such as keeping the connection alive. The thread will call the message arrived callback function in order 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: XPD621