Convert Figma logo to code with AI

eclipse-paho logopaho.mqtt.java

Eclipse Paho Java MQTT client library. Paho is an Eclipse IoT project.

2,234
911
2,234
395

Top Related Projects

A Java MQTT Client

34,302

Netty project - an event-driven asynchronous network application framework

7,823

Efficient reliable UDP unicast, UDP multicast, and IPC message transport

Quick Overview

The eclipse-paho/paho.mqtt.java repository is an MQTT client library written in Java. It provides a client implementation for the MQTT (Message Queuing Telemetry Transport) protocol, allowing Java applications to connect to MQTT brokers for publishing and subscribing to messages in IoT and messaging scenarios.

Pros

  • Robust and well-maintained implementation of the MQTT protocol
  • Supports both MQTT 3.1.1 and MQTT 5.0 versions
  • Offers both synchronous and asynchronous APIs for flexibility
  • Includes SSL/TLS support for secure communications

Cons

  • Learning curve for developers new to MQTT concepts
  • Limited built-in support for advanced features like message persistence
  • Dependency management can be complex in some project setups
  • Documentation could be more comprehensive for advanced use cases

Code Examples

  1. Connecting to an MQTT broker:
MqttClient client = new MqttClient("tcp://broker.hivemq.com:1883", MqttClient.generateClientId());
client.connect();
  1. Publishing a message:
String topic = "sensors/temperature";
String payload = "25.5";
MqttMessage message = new MqttMessage(payload.getBytes());
client.publish(topic, message);
  1. Subscribing to a topic:
client.subscribe("sensors/#", (topic, message) -> {
    System.out.println("Received message on topic: " + topic);
    System.out.println("Message: " + new String(message.getPayload()));
});

Getting Started

To use Paho MQTT Java in your project, add the following dependency to your Maven pom.xml:

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

For Gradle, add this to your build.gradle:

implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'

Then, you can create a simple MQTT client:

import org.eclipse.paho.client.mqttv3.*;

public class SimpleMqttClient {
    public static void main(String[] args) {
        try {
            MqttClient client = new MqttClient("tcp://broker.hivemq.com:1883", MqttClient.generateClientId());
            client.connect();
            System.out.println("Connected to MQTT broker");
            // Use the client for publishing or subscribing
            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}

This example connects to a public MQTT broker, prints a success message, and then disconnects.

Competitor Comparisons

A Java MQTT Client

Pros of mqtt-client

  • Lightweight and simple API, making it easier to use for basic MQTT operations
  • Better support for non-blocking operations and asynchronous programming
  • More active development and recent updates

Cons of mqtt-client

  • Less comprehensive documentation compared to paho.mqtt.java
  • Fewer advanced features and configuration options
  • Smaller community and ecosystem

Code Comparison

mqtt-client:

MQTT mqtt = new MQTT();
mqtt.setHost("tcp://localhost:1883");
FutureConnection connection = mqtt.futureConnection();
connection.connect().then(() -> {
    // Connected
});

paho.mqtt.java:

MqttClient client = new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
MqttConnectOptions options = new MqttConnectOptions();
client.connect(options);
client.setCallback(new MqttCallback() {
    // Implement callback methods
});

The mqtt-client example showcases its more concise API and support for asynchronous operations, while the paho.mqtt.java example demonstrates its more traditional approach with explicit callback handling.

Both libraries provide MQTT functionality for Java applications, but mqtt-client focuses on simplicity and non-blocking operations, while paho.mqtt.java offers a more comprehensive set of features and configuration options. The choice between them depends on the specific requirements of your project and your preferred programming style.

34,302

Netty project - an event-driven asynchronous network application framework

Pros of Netty

  • More versatile and feature-rich, supporting various protocols beyond MQTT
  • Higher performance and scalability for large-scale applications
  • Extensive community support and active development

Cons of Netty

  • Steeper learning curve due to its complexity and broad feature set
  • Requires more configuration and setup for specific use cases like MQTT

Code Comparison

Paho.mqtt.java (MQTT client connection):

MqttClient client = new MqttClient("tcp://broker.hivemq.com:1883", MqttClient.generateClientId());
client.connect();
client.publish("topic", new MqttMessage("Hello".getBytes()));

Netty (MQTT client connection):

Bootstrap b = new Bootstrap();
b.group(workerGroup)
 .channel(NioSocketChannel.class)
 .handler(new MqttClientInitializer());
ChannelFuture f = b.connect("broker.hivemq.com", 1883).sync();

Summary

Paho.mqtt.java is specifically designed for MQTT communication, making it easier to use for MQTT-focused projects. It provides a straightforward API for MQTT operations but is limited to this protocol.

Netty, on the other hand, is a more general-purpose networking framework that can handle various protocols, including MQTT. It offers higher performance and scalability but requires more setup and has a steeper learning curve. Netty is better suited for complex, high-performance networking applications that may involve multiple protocols.

7,823

Efficient reliable UDP unicast, UDP multicast, and IPC message transport

Pros of Aeron

  • Designed for ultra-low latency and high throughput messaging
  • Supports efficient multicast communication
  • Provides detailed performance metrics and monitoring capabilities

Cons of Aeron

  • Steeper learning curve due to its focus on low-level networking
  • Less widespread adoption compared to MQTT-based solutions
  • May be overkill for simpler messaging scenarios

Code Comparison

Aeron (Java):

final Aeron aeron = Aeron.connect();
final Publication publication = aeron.addPublication("aeron:udp?endpoint=localhost:40123", 10);
final UnsafeBuffer buffer = new UnsafeBuffer(ByteBuffer.allocate(256));
buffer.putStringWithoutLengthAscii(0, "Hello, Aeron!");
publication.offer(buffer);

Paho MQTT (Java):

MqttClient client = new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
client.connect();
MqttMessage message = new MqttMessage("Hello, MQTT!".getBytes());
client.publish("test/topic", message);

Summary

Aeron focuses on high-performance, low-latency messaging, making it suitable for demanding applications like financial trading systems. It offers more control over network communication but requires deeper technical knowledge. Paho MQTT, on the other hand, provides a simpler API for publish-subscribe messaging, making it more accessible for general-purpose applications and IoT scenarios. The choice between the two depends on specific performance requirements and the complexity of the messaging system needed.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Eclipse Paho Java Client

Build Status

The Paho Java Client is an MQTT client library written in Java for developing applications that run on the JVM or other Java compatible platforms such as Android

The Paho Java Client provides two APIs: MqttAsyncClient provides a fully asynchronous API where completion of activities is notified via registered callbacks. MqttClient is a synchronous wrapper around MqttAsyncClient where functions appear synchronous to the application.

Project description:

The Paho project has been created to provide reliable open-source implementations of open and standard messaging protocols aimed at new, existing, and emerging applications for Machine-to-Machine (M2M) and Internet of Things (IoT). Paho reflects the inherent physical and cost constraints of device connectivity. Its objectives include effective levels of decoupling between devices and applications, designed to keep markets open and encourage the rapid growth of scalable Web and Enterprise middleware and applications.

Links

Using the Paho Java Client

Downloading

Eclipse hosts a Nexus repository for those who want to use Maven to manage their dependencies. The released libraries are also available in the Maven Central repository.

Add the repository definition and the dependency definition shown below to your pom.xml.

Replace %REPOURL% with either https://repo.eclipse.org/content/repositories/paho-releases/ for the official releases, or https://repo.eclipse.org/content/repositories/paho-snapshots/ for the nightly snapshots. Replace %VERSION% with the level required .

The latest release version is 1.2.5 and the current snapshot version is 1.2.6-SNAPSHOT.

** Dependency definition for MQTTv3 client **

<project ...>
<repositories>
    <repository>
        <id>Eclipse Paho Repo</id>
        <url>%REPOURL%</url>
    </repository>
</repositories>
...
<dependencies>
    <dependency>
        <groupId>org.eclipse.paho</groupId>
        <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
        <version>%VERSION%</version>
    </dependency>
</dependencies>
</project>

** Dependency definition for MQTTv5 client **

<project ...>
<repositories>
    <repository>
        <id>Eclipse Paho Repo</id>
        <url>%REPOURL%</url>
    </repository>
</repositories>
...
<dependencies>
    <dependency>
        <groupId>org.eclipse.paho</groupId>
        <artifactId>org.eclipse.paho.mqttv5.client</artifactId>
        <version>%VERSION%</version>
    </dependency>
</dependencies>
</project>

If you find that there is functionality missing or bugs in the release version, you may want to try using the snapshot version to see if this helps before raising a feature request or an issue.

Building from source

There are two active branches on the Paho Java git repository, master which is used to produce stable releases, and develop where active development is carried out. By default cloning the git repository will download the master branch, to build from develop make sure you switch to the remote branch: git checkout -b develop remotes/origin/develop

To then build the library run the following maven command: mvn package -DskipTests

This will build the client library without running the tests. The jars for the library, source and javadoc can be found in the following directories:

org.eclipse.paho.client.mqttv3/target
org.eclipse.paho.mqttv5.client/target

Documentation

MQTTv3 reference documentation is online at: http://www.eclipse.org/paho/files/javadoc/index.html

Log and Debug in the Java Client: https://wiki.eclipse.org/Paho/Log_and_Debug_in_the_Java_client

Getting Started

The included code below is a very basic sample that connects to a server and publishes a message using the MQTTv3 synchronous API. More extensive samples demonstrating the use of the MQTTv3 and MQTTv5 Asynchronous API can be found in the org.eclipse.paho.sample directory of the source.

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttPublishSample {

    public static void main(String[] args) {

        String topic        = "MQTT Examples";
        String content      = "Message from MqttPublishSample";
        int qos             = 2;
        String broker       = "tcp://iot.eclipse.org:1883";
        String clientId     = "JavaSample";
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            System.out.println("Connecting to broker: "+broker);
            sampleClient.connect(connOpts);
            System.out.println("Connected");
            System.out.println("Publishing message: "+content);
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            sampleClient.publish(topic, message);
            System.out.println("Message published");
            sampleClient.disconnect();
            System.out.println("Disconnected");
            System.exit(0);
        } catch(MqttException me) {
            System.out.println("reason "+me.getReasonCode());
            System.out.println("msg "+me.getMessage());
            System.out.println("loc "+me.getLocalizedMessage());
            System.out.println("cause "+me.getCause());
            System.out.println("excep "+me);
            me.printStackTrace();
        }
    }
}