乐闻世界logo
搜索文章和话题

How to connect to Mqtt3AsyncClient using HiveMq-mqtt library?

1个答案

1

Steps to Connect to Mqtt3AsyncClient Using the HiveMQ MQTT Library

Step 1: Add Maven Dependency

First, ensure your project includes the HiveMQ MQTT client library. If using Maven, add the following dependency to your pom.xml file:

xml
<dependency> <groupId>com.hivemq</groupId> <artifactId>hivemq-mqtt-client</artifactId> <version>1.2.1</version> </dependency>

Check for the latest version to ensure you are using the most recent library.

Step 2: Create Mqtt3AsyncClient Instance

Create an instance of Mqtt3AsyncClient using the HiveMQ MQTT client library. This can be achieved with the MqttClient.builder() method:

java
import com.hivemq.client.mqtt.mqtt3.Mqtt3AsyncClient; import com.hivemq.client.mqtt.MqttClient; import com.hivemq.client.mqtt.mqtt3.Mqtt3ClientBuilder; public class MqttExample { public static void main(String[] args) { Mqtt3AsyncClient client = MqttClient.builder() .useMqttVersion3() .identifier(UUID.randomUUID().toString()) // Client identifier .serverHost("broker.hivemq.com") // MQTT server address .serverPort(1883) // MQTT server port .buildAsync(); } }

Step 3: Connect to MQTT Server

Use the connect method to asynchronously connect to the MQTT server. You can also add additional connection options using Mqtt3Connect, such as clean session and keep-alive interval.

java
import com.hivemq.client.mqtt.mqtt3.message.connect.connack.Mqtt3ConnAck; public class MqttExample { public static void main(String[] args) { // Create Mqtt3AsyncClient instance Mqtt3AsyncClient client = MqttClient.builder() .useMqttVersion3() .identifier(UUID.randomUUID().toString()) .serverHost("broker.hivemq.com") .serverPort(1883) .buildAsync(); // Asynchronously connect to MQTT server client.connectWith() .cleanSession(true) .keepAlive(10) .send() .whenComplete((connAck, throwable) -> { if (throwable != null) { System.out.println("Connection failed: " + throwable.getMessage()); } else { System.out.println("Connected successfully: " + connAck); // Handling after connection } }); } }

Step 4: Handle Business Logic After Connection

After successfully connecting to the server, begin subscribing to topics or publishing messages. For example, subscribe to a topic:

java
client.subscribeWith() .topicFilter("test/topic") .callback(publish -> { System.out.println("Received message: " + new String(publish.getPayloadAsBytes())); }) .send() .whenComplete((subAck, throwable) -> { if (throwable != null) { System.out.println("Subscription failed: " + throwable.getMessage()); } else { System.out.println("Subscription successful"); } });

The following are the basic steps for connecting and interacting with Mqtt3AsyncClient using the HiveMQ MQTT library. With this client library, you can flexibly handle various MQTT-related business requirements, such as device communication and IoT data exchange.

2024年8月16日 21:31 回复

你的答案