This component had officially released in the Vert.x stack, just following dependency to the dependencies section of your build descriptor:
-
Maven (in your
pom.xml):
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-mqtt</artifactId>
<version>${maven.version}</version>
</dependency>-
Gradle (in your
build.gradlefile):
compile "io.vertx:vertx-mqtt:${maven.version}"This component provides a server which is able to handle connections, communication and messages exchange with remote MQTT clients. Its API provides a bunch of events related to raw protocol messages received by clients and exposes some features in order to send messages to them.
At the moment of writing, it supports all MQTT version 5.0 features except AUTH message which is yet to be implemented.
It’s not a fully featured MQTT broker but can be used for building something like that or for protocol translation.
|
Warning
|
this module has the tech preview status, this means the API can change between versions. |
This example shows how it’s possible to handle the connection request from a remote MQTT client. First, an {@link io.vertx.mqtt.MqttServer} instance is created and the {@link io.vertx.mqtt.MqttServer#endpointHandler(io.vertx.core.Handler)} method is used to specify the handler called when a remote client sends a CONNECT message for connecting to the server itself. The {@link io.vertx.mqtt.MqttEndpoint} instance, provided as parameter to the handler, brings all main information related to the CONNECT message like client identifier, username/password, "will" information, clean session flag, protocol version and, "keep alive" timeout and CONNECT message properties (for MQTT version 5.0). Inside that handler, the endpoint instance provides the {@link io.vertx.mqtt.MqttEndpoint#accept(boolean)} method for replying to the remote client with the corresponding CONNACK message : in this way, the connection is established. Finally, the server is started using the {@link io.vertx.mqtt.MqttServer#listen()} method with the default behavior (on localhost and default MQTT port 1883). The same method allows to specify an handler in order to check if the server is started properly or not.
{@link examples.VertxMqttServerExamples#example1}The same endpoint instance provides the {@link io.vertx.mqtt.MqttEndpoint#disconnectMessageHandler(io.vertx.core.Handler)} for specifying the handler called when the remote client sends a DISCONNECT message in order to disconnect from the server; this handler takes {@link io.vertx.mqtt.messages.MqttDisconnectMessage} as a parameter.
{@link examples.VertxMqttServerExamples#example2}If MQTT version 5.0 or newer is used server can send DISCONNECT message to client with the reason code and properties using {@link io.vertx.mqtt.MqttEndpoint#disconnect(MqttDisconnectReasonCode, MqttProperties)}.
The server has the support for accepting connection requests through the SSL/TLS protocol for authentication and encryption. In order to do that, the {@link io.vertx.mqtt.MqttServerOptions} class provides the {@link io.vertx.mqtt.MqttServerOptions#setSsl(boolean)} method for setting the usage of SSL/TLS (passing 'true' as value) and some other useful methods for providing server certificate and related private key (as Java key store reference, PEM or PFX format). In the following example, the {@link io.vertx.mqtt.MqttServerOptions#setKeyCertOptions(io.vertx.core.net.KeyCertOptions)} method is used in order to pass the certificates in PEM format. This method requires an instance of the possible implementations of the {@link io.vertx.core.net.KeyCertOptions} interface and in this case the {@link io.vertx.core.net.PemKeyCertOptions} class is used in order to provide the path for the server certificate and the private key with the correspondent {@link io.vertx.core.net.PemKeyCertOptions#setCertPath(java.lang.String)} and {@link io.vertx.core.net.PemKeyCertOptions#setKeyPath(java.lang.String)} methods. The MQTT server is started passing the Vert.x instance as usual and the above MQTT options instance to the creation method.
{@link examples.VertxMqttServerExamples#example3}If you want to support connections via WebSockets, you can enable this via {@link io.vertx.mqtt.MqttServerOptions},
too. By passing true to {@link io.vertx.mqtt.MqttServerOptions#setUseWebSocket(boolean)}, it will listen for
websocket connections on the path /mqtt.
As with other setup configurations, the resulting endpoint connections and related disconnection are managed the same way as regular connections.
{@link examples.VertxMqttServerExamples#example11}After a connection is established between client and server, the client can send a subscription request for a topic
using the SUBSCRIBE message. The {@link io.vertx.mqtt.MqttEndpoint} interface allows to specify a handler for the
incoming subscription request using the {@link io.vertx.mqtt.MqttEndpoint#subscribeHandler(io.vertx.core.Handler)} method.
Such handler receives an instance of the {@link io.vertx.mqtt.messages.MqttSubscribeMessage} interface which brings
the list of topics with the related subscription options as desired by the client.
Subscription options include QoS level and related flags and for MQTT version 5.0 also additional flags,
such as noLocal and retainAsPublished.
Finally, the endpoint instance provides the {@link io.vertx.mqtt.MqttEndpoint#subscribeAcknowledge(int, java.util.List, MqttProperties)} method
for replying to the client with the related SUBACK message containing the reason code
(which is either QoS level or error code - separate per each topic or pattern) and message properties.
{@link examples.VertxMqttServerExamples#example4}In the same way, it’s possible to use the {@link io.vertx.mqtt.MqttEndpoint#unsubscribeHandler(io.vertx.core.Handler)} method on the endpoint in order to specify the handler called when the client sends an UNSUBSCRIBE message. This handler receives an instance of the {@link io.vertx.mqtt.messages.MqttUnsubscribeMessage} interface as parameter with the list of topics to unsubscribe. Finally, the endpoint instance provides the {@link io.vertx.mqtt.MqttEndpoint#unsubscribeAcknowledge(int)} and {@link io.vertx.mqtt.MqttEndpoint#unsubscribeAcknowledge(int, java.util.List, MqttProperties)} methods for replying to the client with the related UNSUBACK message - either simply acknowledging all unsubscriptions, or specifying the reasons per each topic and the properties in the UNSUBSCRIBE request (supported in MQTT v 5.0 or later).
{@link examples.VertxMqttServerExamples#example5}In order to handle incoming messages published by the remote client, the {@link io.vertx.mqtt.MqttEndpoint} interface provides the {@link io.vertx.mqtt.MqttEndpoint#publishHandler(io.vertx.core.Handler)} method for specifying the handler called when the client sends a PUBLISH message. This handler receives an instance of the {@link io.vertx.mqtt.messages.MqttPublishMessage} interface as parameter with the payload, the QoS level, the duplicate and retain flags, message properties.
If the QoS level is 0 (AT_MOST_ONCE), there is no need from the endpoint to reply the client.
If the QoS level is 1 (AT_LEAST_ONCE), the endpoind needs to reply with a PUBACK message using the available {@link io.vertx.mqtt.MqttEndpoint#publishAcknowledge(int)} or {@link io.vertx.mqtt.MqttEndpoint#publishAcknowledge(int, MqttPubAckReasonCode, MqttProperties)} method.
If the QoS level is 2 (EXACTLY_ONCE), the endpoint needs to reply with a PUBREC message using the available {@link io.vertx.mqtt.MqttEndpoint#publishReceived(int)} or {@link io.vertx.mqtt.MqttEndpoint#publishReceived(int, MqttPubRecReasonCode, MqttProperties)} method; in this case the same endpoint should handle the PUBREL message received from the client as well (the remote client sends it after receiving the PUBREC from the endpoint) and it can do that specifying the handler through the {@link io.vertx.mqtt.MqttEndpoint#publishReleaseHandler(io.vertx.core.Handler)} or {@link io.vertx.mqtt.MqttEndpoint#publishReleaseMessageHandler(io.vertx.core.Handler)} method - depending on whether the server needs access to MQTT version 5.0 extended capabilities (reason code, message properties). In order to close the QoS level 2 delivery, the endpoint can use the {@link io.vertx.mqtt.MqttEndpoint#publishComplete(int)} or {@link io.vertx.mqtt.MqttEndpoint#publishComplete(int, MqttPubCompReasonCode, MqttProperties)} method for sending the PUBCOMP message to the client.
{@link examples.VertxMqttServerExamples#example6}The endpoint can publish a message to the remote client (sending a PUBLISH message) using the {@link io.vertx.mqtt.MqttEndpoint#publish(java.lang.String, io.vertx.core.buffer.Buffer, io.netty.handler.codec.mqtt.MqttQoS, boolean, boolean)} method which takes the following input parameters : the topic to publish, the payload, the QoS level, the duplicate and retain flags. If you’re using MQTT version 5.0 or newer and you’d like to specify message properties you can use {@link io.vertx.mqtt.MqttEndpoint#publish(java.lang.String, io.vertx.core.buffer.Buffer, io.netty.handler.codec.mqtt.MqttQoS, boolean, boolean, int, MqttProperties)} method instead which takes message ID and message properties in addition to the previously described method.
If the QoS level is 0 (AT_MOST_ONCE), the endpoint won’t be receiving any feedback from the client.
If the QoS level is 1 (AT_LEAST_ONCE), the endpoint needs to handle the PUBACK message received from the client in order to receive final acknowledge of delivery. It’s possible using the {@link io.vertx.mqtt.MqttEndpoint#publishAcknowledgeHandler(io.vertx.core.Handler)} or {@link io.vertx.mqtt.MqttEndpoint#publishAcknowledgeMessageHandler(io.vertx.core.Handler)} method specifying such a handler.
If the QoS level is 2 (EXACTLY_ONCE), the endpoint needs to handle the PUBREC message received from the client. The {@link io.vertx.mqtt.MqttEndpoint#publishReceivedHandler(io.vertx.core.Handler)} and {@link io.vertx.mqtt.MqttEndpoint#publishReceivedMessageHandler(io.vertx.core.Handler)} methods allow to specify the handler for that. Inside that handler, the endpoint can use the {@link io.vertx.mqtt.MqttEndpoint#publishRelease(int)} or {@link io.vertx.mqtt.MqttEndpoint#publishRelease(int, MqttPubRelReasonCode, MqttProperties)} method for replying to the client with the PUBREL message. The last step is to handle the PUBCOMP message received from the client as final acknowledge for the published message; it’s possible using the {@link io.vertx.mqtt.MqttEndpoint#publishCompletionHandler(io.vertx.core.Handler)} or {@link io.vertx.mqtt.MqttEndpoint#publishCompletionMessageHandler(io.vertx.core.Handler)} for specifying the handler called when the final PUBCOMP message is received.
{@link examples.VertxMqttServerExamples#example7}The underlying MQTT keep alive mechanism is handled by the server internally. When the CONNECT message is received, the server takes care of the keep alive timeout specified inside that message in order to check if the client doesn’t send messages in such timeout. At same time, for every PINGREQ received, the server replies with the related PINGRESP.
Even if there is no need for the high level application to handle that, the {@link io.vertx.mqtt.MqttEndpoint} interface provides the {@link io.vertx.mqtt.MqttEndpoint#pingHandler(io.vertx.core.Handler)} method for specifying an handler called when a PINGREQ message is received from the client. It’s just a notification to the application that the client isn’t sending meaningful messages but only pings for keeping alive; in any case the PINGRESP is automatically sent by the server internally as described above.
{@link examples.VertxMqttServerExamples#example8}The {@link io.vertx.mqtt.MqttServer} interface provides the {@link io.vertx.mqtt.MqttServer#close()} method that can be used for closing the server; it stops to listen for incoming connections and closes all the active connections with remote clients. This method is asynchronous and one overload provides the possibility to specify a complention handler that will be called when the server is really closed.
{@link examples.VertxMqttServerExamples#example9}After a connection is established between client and server, the client can send an auth packet to server using the AUTH message. The {@link io.vertx.mqtt.MqttEndpoint} interface allows to specify a handler for the incoming auth packet using the {@link io.vertx.mqtt.MqttEndpoint#authenticationExchangeHandler(io.vertx.core.Handler)} method. Such handler receives an instance of the {@link io.vertx.mqtt.messages.MqttAuthenticationExchangeMessage} interface which brings the reason code, the authentication method and data. The server could continue to send AUTH packet using the {@link io.vertx.mqtt.MqttEndpoint#authenticationExchange(io.vertx.mqtt.messages.MqttAuthenticationExchangeMessage)} for authentication or just passed it.
{@link examples.VertxMqttServerExamples#example14}If you’re creating MQTT servers from inside verticles, those servers will be automatically closed when the verticle is undeployed.
The handlers related to the MQTT server are always executed in the same event loop thread. It means that on a system with more cores, only one instance is deployed so only one core is used. In order to use more cores, it’s possible to deploy more instances of the MQTT server.
It’s possible to do that programmatically:
{@link examples.VertxMqttServerExamples#example10}or using a verticle specifying the number of instances:
{@link examples.VertxMqttServerExamples#example11}What’s really happen is that even only MQTT server is deployed but as incoming connections arrive, Vert.x distributes them in a round-robin fashion to any of the connect handlers executed on different cores.
This component provides an MQTT client which is compliant with the 3.1.1 and 5.0 specs. Its API provides a bunch of methods for connecting/disconnecting to a broker, publishing messages (with all three different levels of QoS) and subscribing to topics. MQTT 5.0 features such as user properties, reason codes, subscription options, subscription identifiers, topic aliases and automatic server redirect are supported in addition to the 3.1.1 baseline.
|
Warning
|
This module has the tech preview status, this means the API can change between versions. |
The client gives you opportunity to connect to a server and disconnect from it. Also, you could specify things like the host and port of a server you would like to connect to passing instance of {@link io.vertx.mqtt.MqttClientOptions} as a param through constructor.
This example shows how you could connect to a server and disconnect from it using Vert.x MQTT client and calling {@link io.vertx.mqtt.MqttClient#connect(int, java.lang.String)} and {@link io.vertx.mqtt.MqttClient#disconnect()} methods.
{@link examples.VertxMqttClientExamples#example1}|
Note
|
The default address of the server provided by {@link io.vertx.mqtt.MqttClientOptions} is localhost:1883 and localhost:8883 if you are using SSL/TSL. |
Now, lest go deeper and take look at this example:
{@link examples.VertxMqttClientExamples#example2}Here we have the example of usage of {@link io.vertx.mqtt.MqttClient#subscribe(java.lang.String, int)} method. In order to receive messages from rpi2/temp topic we call {@link io.vertx.mqtt.MqttClient#subscribe(java.lang.String, int)} method. Although, to handle received messages from server you need to provide a handler, which will be called each time you have a new messages in the topics you subscribe on. As this example shows, handler could be provided via {@link io.vertx.mqtt.MqttClient#publishHandler(io.vertx.core.Handler)} method.
If you would like to publish some message into topic then {@link io.vertx.mqtt.MqttClient#publish(java.lang.String, io.vertx.core.buffer.Buffer, io.netty.handler.codec.mqtt.MqttQoS, boolean, boolean)} should be called. Let’s take a look at the example:
{@link examples.VertxMqttClientExamples#example3}In the example, we send message to topic with name "temperature".
After a connection is established between client and server, the client can send an auth request to server using the {@link io.vertx.mqtt.MqttClient#authenticationExchange(io.vertx.mqtt.messages.codes.MqttAuthenticateReasonCode,io.netty.handler.codec.mqtt.MqttProperties)} for authentication. The Server may return an AUTH packet. The {@link io.vertx.mqtt.MqttClient} interface allows to specify a handler for the incoming auth packet using the {@link io.vertx.mqtt.MqttClient#authenticationExchangeHandler(io.vertx.core.Handler)} method. Such handler receives an instance of the {@link io.vertx.mqtt.messages.MqttAuthenticationExchangeMessage} interface which brings the reason code, the authentication method and data.
{@link examples.VertxMqttClientExamples#example10}In order to keep connection with server you should time to time send something to server otherwise server will close the connection. The right way to keep connection alive is a {@link io.vertx.mqtt.MqttClient#ping()} method.
|
Important
|
By default, your client keep connections with server automatically. That means that you don’t need to call {@link io.vertx.mqtt.MqttClient#ping()} in order to keep connections with server. The {@link io.vertx.mqtt.MqttClient} will do it for you. |
If you want to disable this feature then you should call {@link io.vertx.mqtt.MqttClientOptions#setAutoKeepAlive(boolean)} with false as argument:
{@link examples.VertxMqttClientExamples#example4}-
publish is completed
You could provide handler by calling {@link io.vertx.mqtt.MqttClient#publishCompletionHandler(io.vertx.core.Handler)}. The handler will be called each time publish is completed. This one is pretty useful because you could see the packetId of just received PUBACK or PUBCOMP packet.
{@link examples.VertxMqttClientExamples#example5}WarningThe handler WILL NOT BE CALLED if sent publish packet with QoS=0. -
subscribe completed
{@link examples.VertxMqttClientExamples#example6} -
unsubscribe completed
{@link examples.VertxMqttClientExamples#example7} -
unsubscribe sent
{@link examples.VertxMqttClientExamples#example8} -
PINGRESP received
{@link examples.VertxMqttClientExamples#example9}
You can connect to an MQTT server using TLS by configuring the client TCP options, make sure to set:
-
the SSL flag
-
the server certificate or the trust all flag
-
the hostname verification algorithm to
"HTTPS"if you want to verify the server identity otherwise""
{@link examples.VertxMqttClientExamples#tls}|
Note
|
More details on the TLS client config can be found here |
{@link examples.VertxMqttServerExamples#example13}If your servers are behind haproxy or nginx and you want to get the client’s original ip and port, then you need to set setUseProxyProtocol to true
|
Important
|
To enable this feature, you need to add dependency netty-codec-haproxy, but it is not introduced by default, so you need to manually add it
|
-
Maven (in your
pom.xml):
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-codec-haproxy</artifactId>
<version>${maven.version}</version>
</dependency>-
Gradle (in your
build.gradlefile):
compile "io.netty:netty-codec-haproxy:${maven.version}"|
Warning
|
this section is new and currently in tech preview, in other words the API is subject to be change until it reaches maturity |
The client targets MQTT 3.1.1 by default. To switch the wire protocol to MQTT 5.0, set the protocol version on {@link io.vertx.mqtt.MqttClientOptions} before creating the client:
MqttClientOptions options = new MqttClientOptions();
options.setVersion(io.netty.handler.codec.mqtt.MqttVersion.MQTT_5.protocolLevel()); // 5
MqttClient client = MqttClient.create(vertx, options);Only the values 4 (MQTT 3.1.1) and 5 (MQTT 5.0) are accepted by
{@link io.vertx.mqtt.MqttClientOptions#setVersion(int)}.
When using MQTT 5.0, the following CONNECT properties can be configured on {@link io.vertx.mqtt.MqttClientOptions}:
-
{@link io.vertx.mqtt.MqttClientOptions#setSessionExpireInterval(java.lang.Long)} — Session Expiry Interval (seconds)
-
{@link io.vertx.mqtt.MqttClientOptions#setReceiveMaximum(java.lang.Integer)} — maximum number of in-flight QoS 1/2 PUBLISH packets the client is willing to receive
-
{@link io.vertx.mqtt.MqttClientOptions#setMaximumPacketSize(java.lang.Long)} — maximum packet size the client will accept from the server
-
{@link io.vertx.mqtt.MqttClientOptions#setTopicAliasMaximum(java.lang.Integer)} — highest topic alias value the client will accept from the server
-
{@link io.vertx.mqtt.MqttClientOptions#setRequestResponseInformation(java.lang.Boolean)} / {@link io.vertx.mqtt.MqttClientOptions#setRequestProblemInformation(java.lang.Boolean)}
-
{@link io.vertx.mqtt.MqttClientOptions#setAuthenticationMethod(java.lang.String)} / {@link io.vertx.mqtt.MqttClientOptions#setAuthenticationData(io.vertx.core.buffer.Buffer)}
User properties can be attached to the CONNECT packet by using the
{@link io.vertx.mqtt.MqttClient#connect(int, java.lang.String, java.lang.String, java.util.Map)} overload that takes a Map<String, String> of user properties.
The result of the CONNECT is delivered as a {@link io.vertx.mqtt.messages.MqttConnAckMessage} which, on MQTT 5.0, exposes the full set of server-advertised properties (Receive Maximum, Maximum QoS, Retain Available, Maximum Packet Size, Assigned Client Identifier, Topic Alias Maximum, Reason String, Wildcard / Shared Subscription Available, Subscription Identifiers Available, Server Keep Alive, Response Information, Server Reference, Authentication Method/Data and user properties).
The MQTT 5.0 Session Expiry Interval (in seconds) replaces the 3.1.1 clean session flag and tells the broker how long session state (subscriptions, queued QoS 1/2 messages) must survive after the network connection is closed. It is set on {@link io.vertx.mqtt.MqttClientOptions} before connecting:
MqttClientOptions options = new MqttClientOptions();
options.setVersion(io.netty.handler.codec.mqtt.MqttVersion.MQTT_5.protocolLevel());
options.setCleanSession(false); // required to keep a persistent session
options.setSessionExpireInterval(3600L); // keep the session for one hour after disconnect
MqttClient client = MqttClient.create(vertx, options);Semantics follow MQTT 5.0 §3.1.2.11:
-
null(the default) or0L— the session ends as soon as the network connection ends (equivalent to a clean session). -
a positive value — the session persists for that many seconds after the connection is closed.
-
0xFFFFFFFFL(4_294_967_295L) — the session never expires.
Valid values are in the range 0L..0xFFFFFFFFL; values outside this range cause
{@link io.vertx.mqtt.MqttClientOptions#setSessionExpireInterval(java.lang.Long)} to throw IllegalArgumentException.
The property is only put on the wire when the protocol version is 5; on MQTT 3.1.1 the value is silently ignored and
session persistence is driven exclusively by {@link io.vertx.mqtt.MqttClientOptions#setCleanSession(boolean)}.
The broker may override the requested value: when present, the Session Expiry Interval returned in the CONNACK is the authoritative one for the lifetime of the session and can be inspected via {@link io.vertx.mqtt.messages.MqttConnAckMessage#sessionExpiryInterval()}.
Receive Maximum (MQTT 5.0 §3.1.2.11.3) is the per-direction flow-control window for QoS 1 and QoS 2 PUBLISH packets: it is the maximum number of in-flight messages (sent but not yet fully acknowledged) the peer is willing to accept. Each side advertises its own limit and must honour the limit advertised by the other.
Client side — set on {@link io.vertx.mqtt.MqttClientOptions} before connecting:
MqttClientOptions options = new MqttClientOptions();
options.setVersion(io.netty.handler.codec.mqtt.MqttVersion.MQTT_5.protocolLevel());
options.setReceiveMaximum(20); // accept at most 20 concurrent in-flight QoS 1/2 PUBLISHes from the server
MqttClient client = MqttClient.create(vertx, options);-
The value is a positive 16-bit integer; valid range is
1..65535. Values outside0..0xFFFFare rejected by {@link io.vertx.mqtt.MqttClientOptions#setReceiveMaximum(java.lang.Integer)} withIllegalArgumentException. -
null(the default) omits the property from the CONNECT, which per spec means "no limit" (65535). -
The property is only put on the wire when the protocol version is
5; on MQTT 3.1.1 the value is ignored.
Server side — the value the broker advertises in its CONNACK is enforced automatically when calling {@link io.vertx.mqtt.MqttClient#publish(java.lang.String, io.vertx.core.buffer.Buffer, io.netty.handler.codec.mqtt.MqttQoS, boolean, boolean)} for QoS 1 or 2:
-
if the number of in-flight messages already equals the server’s Receive Maximum, the returned
Futurefails with an {@link io.vertx.mqtt.MqttException} whose code isMQTT_INFLIGHT_QUEUE_FULL; -
QoS 0 PUBLISH packets are never gated by this limit (they have no acknowledgement);
-
if the CONNACK omits the property, the client treats it as unlimited (
Integer.MAX_VALUEinternally); -
the negotiated value can be inspected via {@link io.vertx.mqtt.messages.MqttConnAckMessage#receiveMaximum()}.
|
Note
|
this is independent from (and applied in addition to) the existing client-local cap configured via
{@link io.vertx.mqtt.MqttClientOptions#setMaxInflightQueue(int)}; whichever limit is hit first triggers the
MQTT_INFLIGHT_QUEUE_FULL failure.
|
Will message configuration has been moved to a dedicated {@link io.vertx.mqtt.MqttClientWillOptions} object that supports
both 3.1.1 fields (topic, payload, QoS, retain) and the MQTT 5.0 will properties: Will Delay Interval,
Payload Format Indicator, Content Type, Response Topic, Correlation Data and user properties. The will options can be
set via {@link io.vertx.mqtt.MqttClientOptions#setWillOptions(io.vertx.mqtt.MqttClientWillOptions)}; the legacy
setWillTopic / setWillMessage / setWillQoS / setWillRetain setters are still available for 3.1.1 compatibility.
|
Important
|
The standalone willFlag setter has been removed on the client side — the presence of a will is now derived
from willTopic and willPayload. In JSON, the will is serialized as a nested willOptions object.
|
When using MQTT 5.0, outgoing PUBLISH packets can carry additional properties (Payload Format Indicator, Message Expiry
Interval, Content Type, Response Topic, Correlation Data, user properties, Topic Alias). Use
{@link io.vertx.mqtt.MqttClient#publish(java.lang.String, io.vertx.core.buffer.Buffer, io.netty.handler.codec.mqtt.MqttQoS, boolean, boolean, io.netty.handler.codec.mqtt.MqttProperties)}
to pass an MqttProperties instance alongside the payload. The Subscription Identifier property is not valid on a
client-originated PUBLISH — see the dedicated section below.
The acknowledgement flow now exposes the full typed messages including reason code and properties:
-
{@link io.vertx.mqtt.MqttClient#publishAckMessageHandler(io.vertx.core.Handler)} — PUBACK (QoS 1)
-
{@link io.vertx.mqtt.MqttClient#publishRecMessageHandler(io.vertx.core.Handler)} — PUBREC (QoS 2)
-
{@link io.vertx.mqtt.MqttClient#publishCompMessageHandler(io.vertx.core.Handler)} — PUBCOMP (QoS 2)
These fire alongside the existing {@link io.vertx.mqtt.MqttClient#publishCompletionHandler(io.vertx.core.Handler)} so that 3.1.1 code keeps working. On the inbound side, the client can also acknowledge an incoming PUBLISH with reason code and properties via {@link io.vertx.mqtt.MqttClient#publishAcknowledge(int, io.vertx.mqtt.messages.codes.MqttPubAckReasonCode, io.netty.handler.codec.mqtt.MqttProperties)}, {@link io.vertx.mqtt.MqttClient#publishReceived(int, io.vertx.mqtt.messages.codes.MqttPubRecReasonCode, io.netty.handler.codec.mqtt.MqttProperties)}, {@link io.vertx.mqtt.MqttClient#publishRelease(int, io.vertx.mqtt.messages.codes.MqttPubRelReasonCode, io.netty.handler.codec.mqtt.MqttProperties)} and {@link io.vertx.mqtt.MqttClient#publishComplete(int, io.vertx.mqtt.messages.codes.MqttPubCompReasonCode, io.netty.handler.codec.mqtt.MqttProperties)}.
Two MQTT 5.0 specific overloads of subscribe are available:
-
{@link io.vertx.mqtt.MqttClient#subscribe(java.util.Map, io.netty.handler.codec.mqtt.MqttProperties)} — same QoS map as the 3.1.1 API plus a properties object (for example a Subscription Identifier).
-
{@link io.vertx.mqtt.MqttClient#subscribe(java.util.List, io.netty.handler.codec.mqtt.MqttProperties)} — for fine-grained subscription options. Each
MqttTopicSubscriptioncarries anMqttSubscriptionOptionthat encodes QoS plus the v5 flags (No Local,Retain As Published,Retain Handling).
unsubscribe has a matching {@link io.vertx.mqtt.MqttClient#unsubscribe(java.util.List, io.netty.handler.codec.mqtt.MqttProperties)} overload
that accepts properties. The SUBACK and UNSUBACK responses expose per-topic reason codes and properties via
{@link io.vertx.mqtt.messages.MqttSubAckMessage} and {@link io.vertx.mqtt.messages.MqttUnsubAckMessage}; for UNSUBACK
the dedicated {@link io.vertx.mqtt.MqttClient#unsubscribeCompletionMessageHandler(io.vertx.core.Handler)} delivers the
full typed message.
The Subscription Identifier (MQTT 5.0 §3.8.2.1.2) is a positive integer that the client attaches to a SUBSCRIBE request; the broker then echoes it back on every PUBLISH that matches that subscription (§3.3.2.3.8), so the client can route incoming messages to the correct handler without re-parsing the topic.
It is set as a property on the SUBSCRIBE packet, not on the PUBLISH:
MqttProperties subProps = new MqttProperties();
subProps.add(new MqttProperties.IntegerProperty(
MqttProperties.MqttPropertyType.SUBSCRIPTION_IDENTIFIER.value(),
42));
client.subscribe(java.util.Collections.singletonMap("sensors/+/temperature", 1), subProps);The same subProps can be passed to the list-based overload
{@link io.vertx.mqtt.MqttClient#subscribe(java.util.List, io.netty.handler.codec.mqtt.MqttProperties)} when you need to
combine the identifier with per-topic v5 subscription options (No Local, Retain As Published, Retain Handling).
On the receiving side, read the identifier from the incoming PUBLISH:
client.publishHandler(msg -> {
MqttProperties.MqttProperty<?> p = msg.properties()
.getProperty(MqttProperties.MqttPropertyType.SUBSCRIPTION_IDENTIFIER.value());
if (p != null) {
int id = (Integer) p.value(); // 42
// route based on id
}
});If the broker matches the PUBLISH against more than one subscription, the property is repeated — use
properties().getProperties(SUBSCRIPTION_IDENTIFIER.value()) to obtain the full list.
Preconditions enforced by the client (an attempt to subscribe with a Subscription Identifier that violates them fails
the returned Future with {@link io.vertx.mqtt.MqttException}):
-
the protocol version must be
5(MqttClientOptions.setVersion(5)) — otherwiseMQTT_SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED; -
the broker must not have advertised
SUBSCRIPTION_IDENTIFIER_AVAILABLE=0in the CONNACK; the negotiated value is exposed by {@link io.vertx.mqtt.messages.MqttConnAckMessage#subscriptionIdentifierAvailable()} and, when missing, defaults to "available" per spec.
Topic aliases (MQTT 5.0 §3.3.2.3.4) are managed automatically in both directions.
Server → client: when an incoming PUBLISH carries a Topic Alias property, the alias-to-topic mapping is cached and
subsequent packets that reuse the same alias with an empty topic name are transparently re-expanded before being delivered
to the {@link io.vertx.mqtt.MqttClient#publishHandler(io.vertx.core.Handler)}. The maximum number of aliases the broker
may use is controlled by {@link io.vertx.mqtt.MqttClientOptions#setTopicAliasMaximum(java.lang.Integer)}; an alias value
of 0 or one above the negotiated maximum results in a DISCONNECT with reason code TOPIC_ALIAS_INVALID.
Client → server: when the broker advertises a non-zero Topic Alias Maximum in its CONNACK, the client transparently
assigns aliases to outgoing PUBLISH packets. The first PUBLISH for a given topic carries the full topic name plus a newly
allocated Topic Alias property; subsequent PUBLISH packets on the same topic are sent with an empty topic name and just
the alias. If the alias pool advertised by the broker is exhausted, further topics are published with their full name
and no alias. This is fully internal — applications keep calling
{@link io.vertx.mqtt.MqttClient#publish(java.lang.String, io.vertx.core.buffer.Buffer, io.netty.handler.codec.mqtt.MqttQoS, boolean, boolean)}
with the real topic name and pay no attention to aliases.
MQTT 5.0 §4.10 standardises a request/response pattern on top of regular PUBLISH packets, using three new properties: Response Topic, Correlation Data and the optional Response Information hint the broker may advertise to help the client pick a topic prefix. The pattern is fully supported in this client.
If you want the broker to suggest a topic prefix to use as the Response Topic (typically a unique per-client path that
is already covered by the broker’s ACL for that client), set Request Response Information = true on the CONNECT:
MqttClientOptions options = new MqttClientOptions();
options.setVersion(io.netty.handler.codec.mqtt.MqttVersion.MQTT_5.protocolLevel());
options.setRequestResponseInformation(true);
MqttClient client = MqttClient.create(vertx, options);
client.connect(1883, "broker.example.com")
.onSuccess(connack -> {
String prefix = connack.responseInformation(); // null if the broker didn't return any
// e.g. "$share/responses/{clientId}/"
});See {@link io.vertx.mqtt.MqttClientOptions#setRequestResponseInformation(java.lang.Boolean)} and
{@link io.vertx.mqtt.messages.MqttConnAckMessage#responseInformation()}. The broker is free to ignore the request —
treat null as "no hint, pick your own response topic".
The requester subscribes to whatever topic it will use to receive replies, then publishes the request with the two properties set:
// 1. subscribe to the reply channel
String replyTopic = "clients/" + client.clientId() + "/replies";
client.subscribe(replyTopic, 1);
// 2. publish the request
byte[] correlationId = java.util.UUID.randomUUID().toString().getBytes();
MqttProperties reqProps = new MqttProperties();
reqProps.add(new MqttProperties.StringProperty(
MqttProperties.MqttPropertyType.RESPONSE_TOPIC.value(), replyTopic));
reqProps.add(new MqttProperties.BinaryProperty(
MqttProperties.MqttPropertyType.CORRELATION_DATA.value(), correlationId));
client.publish("requests/temperature",
Buffer.buffer("{\"room\":\"kitchen\"}"),
MqttQoS.AT_LEAST_ONCE, false, false, reqProps);Correlation Data is opaque to MQTT — its only purpose is to let the requester pair a reply back to the originating request when several requests are outstanding at the same time.
On the responder side the two properties arrive on the incoming PUBLISH:
client.publishHandler(msg -> {
if (!"requests/temperature".equals(msg.topicName())) return;
String respTopic = ((MqttProperties.StringProperty) msg.properties()
.getProperty(MqttProperties.MqttPropertyType.RESPONSE_TOPIC.value())).value();
byte[] corr = ((MqttProperties.BinaryProperty) msg.properties()
.getProperty(MqttProperties.MqttPropertyType.CORRELATION_DATA.value())).value();
MqttProperties respProps = new MqttProperties();
respProps.add(new MqttProperties.BinaryProperty(
MqttProperties.MqttPropertyType.CORRELATION_DATA.value(), corr));
client.publish(respTopic,
Buffer.buffer("{\"temp\":21.5}"),
MqttQoS.AT_LEAST_ONCE, false, false, respProps);
});A responder that cannot or will not honour the request (missing Response Topic, unsupported payload, etc.) simply does not publish a reply — there is no protocol-level negative ack defined for this pattern.
Back on the requester, the same publishHandler callback receives the reply on replyTopic. Match the Correlation
Data against the value used in the request to route the response to the right caller (e.g. complete a
Promise<Buffer> kept in a Map<ByteBuffer, Promise<Buffer>>).
A handler can be registered to be notified when the server sends a DISCONNECT packet (rather than the client closing the connection itself):
client.disconnectMessageHandler(msg -> {
System.out.println("server disconnected, reason=" + msg.code() + " props=" + msg.properties());
});See {@link io.vertx.mqtt.MqttClient#disconnectMessageHandler(io.vertx.core.Handler)}. The handler fires before {@link io.vertx.mqtt.MqttClient#closeHandler(io.vertx.core.Handler)} and only for server-initiated disconnects. The client can also actively send a DISCONNECT with reason code and properties via {@link io.vertx.mqtt.MqttClient#disconnect(io.vertx.mqtt.messages.codes.MqttDisconnectReasonCode, io.netty.handler.codec.mqtt.MqttProperties)}.
MQTT 5.0 §4.12 introduces an Enhanced Authentication flow built on a new AUTH control packet, designed to support multi-round challenge/response schemes (e.g. SCRAM, Kerberos, mutual proofs) that cannot fit in the single CONNECT exchange used by 3.1.1. The client side fully supports this flow, both during the initial connection (§4.12.1) and for re-authentication on an already established connection (§4.12.2).
The first chunk of authentication data, plus the name of the mechanism, are placed on the CONNECT packet via {@link io.vertx.mqtt.MqttClientOptions}:
-
{@link io.vertx.mqtt.MqttClientOptions#setAuthenticationMethod(java.lang.String)} — UTF-8 name of the mechanism (MQTT 5.0 §3.1.2.11.9). When set, the broker is expected to drive the rest of the exchange with AUTH packets and must fail the connection with
Bad authentication methodif it does not support it. -
{@link io.vertx.mqtt.MqttClientOptions#setAuthenticationData(io.vertx.core.buffer.Buffer)} — opaque binary payload required by the chosen mechanism (MQTT 5.0 §3.1.2.11.10).
The values the broker returns in the CONNACK can be inspected on the resulting
{@link io.vertx.mqtt.messages.MqttConnAckMessage} via authenticationMethod() and authenticationData() — for
mechanisms such as SCRAM, the final server signature (v=…) is typically delivered there.
Register a handler to be notified when the broker sends an AUTH packet — both during the initial handshake (before
CONNACK, while the client is still in CONNECTING state) and during re-authentication on a live connection:
client.authenticationExchangeHandler(msg -> {
// msg.reasonCode() — CONTINUE_AUTHENTICATION / SUCCESS / RE_AUTHENTICATE
// msg.authenticationMethod() — echoed by the broker, must match the negotiated method
// msg.authenticationData() — opaque payload for the mechanism (e.g. SCRAM server-first-message)
});See {@link io.vertx.mqtt.MqttClient#authenticationExchangeHandler(io.vertx.core.Handler)} and {@link io.vertx.mqtt.messages.MqttAuthenticationExchangeMessage}.
The client replies to (or initiates) an AUTH exchange through {@link io.vertx.mqtt.MqttClient#authenticationExchange(io.vertx.mqtt.messages.codes.MqttAuthenticateReasonCode, io.netty.handler.codec.mqtt.MqttProperties)}. It is valid in two phases:
-
Initial enhanced authentication (MQTT 5.0 §4.12.1) — call it from inside the
authenticationExchangeHandlerwhileclient.connect(…)is still in flight. Reply withCONTINUE_AUTHENTICATION(0x18) until the broker terminates the exchange with a CONNACK. The returnedFuturesucceeds as soon as the AUTH frame is on the wire; the overall outcome is the one delivered byclient.connect(…). -
Re-authentication (MQTT 5.0 §4.12.2) — once the connection is established, call it with
RE_AUTHENTICATE(0x19) to restart the authentication exchange without tearing down the underlying TCP connection.
The reason code is supplied via {@link io.vertx.mqtt.messages.codes.MqttAuthenticateReasonCode} (SUCCESS,
CONTINUE_AUTHENTICATION, RE_AUTHENTICATE); the MqttProperties parameter must include the
AUTHENTICATION_METHOD (echoed unchanged for the whole exchange) and, when required by the mechanism, the
AUTHENTICATION_DATA payload.
The following snippet shows how to drive a full SCRAM-SHA-256 handshake (RFC 5802) against an MQTT 5.0 broker that
advertises SCRAM-SHA-256 (for example EMQX with the scram authenticator). The crypto primitives come from the
JDK — no extra dependency is required.
Step 1 — generate the client nonce, build client-first-message and place it on the CONNECT:
String clientNonce = randomBase64(24); // securely random, RFC 5802 §5.1
String clientFirstMessageBare = "n=" + username + ",r=" + clientNonce;
String clientFirstMessage = "n,," + clientFirstMessageBare; // "n,," is the GS2 header
MqttClientOptions options = new MqttClientOptions();
options.setVersion(io.netty.handler.codec.mqtt.MqttVersion.MQTT_5.protocolLevel());
options.setAuthenticationMethod("SCRAM-SHA-256");
options.setAuthenticationData(Buffer.buffer(clientFirstMessage.getBytes(StandardCharsets.UTF_8)));
MqttClient client = MqttClient.create(vertx, options);Step 2 — when the broker replies with server-first-message, compute the client proof and send
client-final-message back through an AUTH packet:
client.authenticationExchangeHandler(msg -> {
// server-first-message: r=<server-nonce>,s=<base64-salt>,i=<iterations>
String serverFirst = new String(msg.authenticationData().getBytes(), StandardCharsets.UTF_8);
Map<String,String> f = parseScram(serverFirst);
String serverNonce = f.get("r");
byte[] salt = Base64.getDecoder().decode(f.get("s"));
int iterations = Integer.parseInt(f.get("i"));
// RFC 5802 §5.1: server MUST extend the client nonce — fail closed otherwise.
if (!serverNonce.startsWith(clientNonce)) throw new SecurityException("bad nonce");
String clientFinalNoProof = "c=biws,r=" + serverNonce; // biws = base64("n,,")
String authMessage = clientFirstMessageBare + "," + serverFirst + "," + clientFinalNoProof;
byte[] saltedPwd = pbkdf2(password, salt, iterations); // PBKDF2-HMAC-SHA-256
byte[] clientKey = hmacSha256(saltedPwd, "Client Key".getBytes());
byte[] storedKey = sha256(clientKey);
byte[] clientSig = hmacSha256(storedKey, authMessage.getBytes());
byte[] clientProof = xor(clientKey, clientSig);
String clientFinal = clientFinalNoProof
+ ",p=" + Base64.getEncoder().encodeToString(clientProof);
MqttProperties props = new MqttProperties();
props.add(new MqttProperties.StringProperty(
MqttProperties.MqttPropertyType.AUTHENTICATION_METHOD.value(), "SCRAM-SHA-256"));
props.add(new MqttProperties.BinaryProperty(
MqttProperties.MqttPropertyType.AUTHENTICATION_DATA.value(),
clientFinal.getBytes(StandardCharsets.UTF_8)));
client.authenticationExchange(MqttAuthenticateReasonCode.CONTINUE_AUTHENTICATION, props);
});
client.connect(1883, "broker.example.com").onSuccess(connack -> {
// authenticated; connack.authenticationData() may carry the SCRAM server-final-message (v=...)
});A complete, runnable version including the SCRAM helper methods (pbkdf2, hmacSha256, sha256, xor, nonce
generation and SASL-name escaping) is available in {@link examples.VertxMqttClientAUTHExamples}.
On the server side AUTH packets are accepted at the wire level (so a broker can be probed without dropping the TCP connection) but {@link io.vertx.mqtt.impl.MqttEndpointImpl} does not currently surface them to user code: {@code handleAuth} is a stub. Implementing an enhanced-authentication endpoint therefore requires extending the endpoint API; the client-side types are already in place so a future server port will not change this section’s API surface.
When the broker returns a CONNACK or DISCONNECT with a Server Reference property (MQTT 5.0 §3.2.2.3.18 / §3.14.2.3.4),
the client can transparently reconnect to one of the servers listed there. This behavior is enabled by default and can be
toggled with {@link io.vertx.mqtt.MqttClientOptions#setAutoServerRedirect(boolean)}. When several references are present
in the comma-separated list, one is picked at random.