Skip to content

Implementing MQTT in Java

by HiveMQ Team
12 min read

Developers can use Java to implement MQTT and enable efficient data exchange in IoT systems. MQTT’s publish/subscribe model uses minimal code and data compared to other protocols and supports real-time communication while using fewer resources. Java is an object-oriented programming language. It’s designed so that compiled Java programs can run on any platform without having to be recompiled. Java is one of the most popular programming languages and is especially useful for client-server web applications.

How to Use an MQTT Java Client Library?

Developers can use an MQTT Java Client Library, such as HiveMQ MQTT Client for Java or Eclipse Paho Java MQTT Client Library, to connect to an MQTT broker, publish data, and subscribe to topics to receive data.

Using the HiveMQ MQTT Client Library for Java

The HiveMQ MQTT Client library for Java will help you handle the communication between your device and the MQTT broker. This library is a popular choice among Java developers due to its reliability and ease of use. It is MQTT 5.0 and MQTT 3.1.1 compatible and is a feature-rich high-performance Java client library with different API flavours and backpressure support.

You can get started with any of the below three API flavors of the HiveMQ MQTT Java Client:

Check out the GitHub and HiveMQ MQTT Client Documentation for more information.

Using Eclipse Paho Java client Library

The Eclipse Foundation also supports a Java client that works for general use of Java, embedded systems, and Android applications. It has two different APIs, an asynchronous API that allows developers to write high-performance code, and an API with a synchronous wrapper that makes it simpler for developers to write applications with concise logic. Paho Java includes options for additional security with TLS and has clients that support both MQTT v3 and MQTT v5. It allows users to write Java applications to connect to a broker, publish messages, and subscribe to topics. The publish/subscribe model means that when a user has subscribed to a topic they will receive new data automatically when it is published to the broker without needing to poll a server regularly to check for new data.

To get started using the Java MQTT client, first you can download the Paho Java library from the Eclipse project page and add it to your Java classpath. Then you can install it using a dependency management tool like Maven, Gradle, or Ivy.

For Maven, add the following code to your pom.xml file.

<repositories>
    <repository>
        <id>Eclipse Paho Repo</id>
     <url>https://repo.eclipse.org/content/repositories/paho-releases/</url>
    </repository>
</repositories>

Then add the following code to your dependencies section:

<dependency>
    <groupId>org.eclipse.paho</groupId>
    <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
    <version>1.0.2</version>
</dependency>

Then, you can create a client instance.

To create a client instance, you need to configure an MQTT broker, either locally or using HiveMQ Cloud Serverless and then use the broker url to instantiate a client.

MqttClient client = new MqttClient(
        "tcp://localhost:1883", //URI
        MqttClient.generateClientId(), //ClientId
        new MemoryPersistence()); //Persistence

How to Connect to an MQTT Broker in Java?

Brokers make MQTT work. They allow each device to only open one connection while sharing data with myriad other devices. If you are new to MQTT and want to understand how an MQTT Broker works, read our Beginner's Guide to MQTT Broker.

HiveMQ’s broker can support up to 200 million connections. HiveMQ has a hosted option, HiveMQ Cloud Serverless, as well as an open-source option, HiveMQ CE.

After you’ve created a client instance, you can connect to a broker with the following code.

client.connect();

You can also check if a client is connected to a broker.

client.isConnected()

To connect more securely using a username and password, you can use the following code.

MqttConnectOptions options = new MqttConnectOptions();
options.setUserName("username");
options.setPassword("password".toCharArray()); 
client.connect(options);

It’s important to note that a username has to be a string and a password has to be converted to a character array.

Once you’ve connected to a broker, you can start publishing messages and subscribing to topics to share information between your IoT devices.

Code Examples of Using MQTT in Java

Publishing MQTT Messages in Java

client.publish(`
"topic", // topic
"payload".getBytes(UTF_8), // payload
2, // QoS level
false // retained?
);

Subscribing MQTT Messages in Java

client.subscribe("#", 1); //topic and QoS level are parameters

The code examples in this post come from our blog post Eclipse Paho Java - MQTT Client Library Encyclopedia and there are many more examples there.

MQTT Security Best Practices While Using Java MQTT Broker

MQTT is built to be an efficient communication protocol and isn’t intrinsically secure, so it’s important to follow security practices when implementing MQTT with Java. Security can be especially important for IoT use cases because IoT devices often have limited memory capacities and computing capabilities. You can use a secure network or VPN to add security to your applications. Another good practice is to use the security standard SSL/TLS for transport-level encryption. This popular standard will encrypt your data as it is transmitted and verify identity on both sides. Developers can also build in security practices at the application level. Using a client identifier, username, and password will improve the security of your applications and let you get all the benefits of MQTT’s efficiency without compromising on security.

Port 8883 is the standard port used for secure MQTT connections. You can specify SSL as the protocol you want to use when you create a client instance. You also need to pass an SSLSocketFactory into MqttOptions.

If you are using the Paho Java Client, it uses standard Java SSL systems and you can also use BouncyCastles and other security libraries if those have APIs you prefer or they are a better fit for your application.

The following code shows broadly how SSL/TLS is set up with Paho Java.

MqttClient client = new MqttClient("ssl://yourbroker:8883", 
MqttClient.generateClientId(), new MemoryPersistence());

SSLContext sslContext = SSLContext.getInstance("SSL");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore keyStore = readKeyStore();
trustManagerFactory.init(keyStore);
sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());

MqttConnectOptions options = new MqttConnectOptions();
options.setSocketFactory(sslContext.getSocketFactory());

client.connect(options);

Use Case Examples for MQTT in Java

Java can be used to implement MQTT for IoT use cases, including remote monitoring, home automation, telemetry, and sensor networks. Java is a very popular programming language and developers can use it to build all kinds of applications, including Android applications. MQTT is lightweight and efficient enough that applications built using Java and MQTT can share data between devices in real time while using limited bandwidth. For example, you could write a Java application to subscribe to temperature data published to an MQTT broker and automate an application to send an alert if an electric car’s battery rises above a set threshold.

Conclusion

Using Java with MQTT lets developers build efficient IoT applications and work with real-time data. When deciding how to build an application, consider your specific requirements, constraints, and project objectives to make an informed choice about using MQTT in your Java projects. Click here to learn more about MQTT Client libraries.

FAQs on Implementing MQTT in Java

Read our blog Implementing MQTT in C to learn how to set up an MQTT client and a broker connection in C.

Read our blog Implementing MQTT in Python to learn how to set up an MQTT client and a broker connection in Python.

Read our blog Implementing MQTT in C# to learn how to set up an MQTT client and a broker connection in C#.

Read our blog Implementing MQTT in Javascript to learn how to set up an MQTT client and a broker connection in Javascript.

HiveMQ Team

The HiveMQ team loves writing about MQTT, Sparkplug, Industrial IoT, protocols, how to deploy our platform, and more. We focus on industries ranging from energy, to transportation and logistics, to automotive manufacturing. Our experts are here to help, contact us with any questions.

Related content:

HiveMQ logo
Review HiveMQ on G2