Publish
How to use an ApplicationMessagePacketBuilder to create and send an Application Message to the broker.
Initial setup¶
Extending the code from the previous chapter, we can add new event handler OnConnected
:
The OnConnected
event is fired when the client successfully connected with its transport, the MQTT protocol negotiation is over and messages can be sent. We will add code to this new callback to publish a new application message.
Simple Publish¶
MQTTClient
has a CreateApplicationMessageBuilder
function to help in the creation and sending of application messages.
- Create the builder with the given topic name.
- Set the payload.
WithPayload
has an overload to accept abyte[]
too to send binary data. - Start sending the application message.
Clients subscribing to the best_mqtt/test_topic topic produces the following output:
Setting QoS Levels¶
Best MQTT supports both sending and receiving all three QoS levels on all supported platforms, including WebGL. We can define the application message's QoS level by using the WithQoS
function:
QoS | Description |
---|---|
AtMostOnceDelivery (QoS 0) | Sent only once by the client, no guarantee the server receives it. |
AtLeastOnceDelivery (QoS 1) | Sent at least once, until receives an acknowledgement from the server that received it. QoS 1 messages might received more than once. |
ExactlyOnceDelivery (QoS 2) | The protocol makes sure that QoS 2 messages are received only once. |
If .WithQoS()
call is not present the plugin sends messages with AtMostOnceDelivery
(QoS 0).
QoS setting of an application message controls only the QoS level between the client and the server. The server can deliver the message to its subscribing clients with different QoS levels.
Content-Type¶
Using the WithContentType
function we can specify what type of content we are sending. It's a textual description of the content. It's usually a MIME content type, but because neither the plugin or the server processing it, its meaning and usage is defined by the sending and receiving application.
Setting Topic Alias¶
To send less data every time a message is published to a topic, a topic-alias can be assigned to the topic name. This way only the topic-alias number is sent instead of the full topic name possibly saving bandwith and processing time. To add a topic name mapping add the following line to the OnConnected handler before creating the application message builder:
When a topic alias added the next message published with the topic will inform the server about the mapping. Consecutive messages will use the mapping by omitting the topic name.
Best use of a topic name mapping is when messages are sent frequently to the topic and/or the topic name is long.