Developing MQTT Clients

MQTT Paho Java Client

Eclipse Paho Java Client is an MQTT client library written in Java (MQTT Java Client), which can be used in JVM or other Java compatible platforms (such as Android ). Eclipse Paho Java Client provides asynchronous and synchronous APIs of MqttAsyncClient and MqttClient.

More details can be found on Paho MQTT Clients Website.

We provide a hello world example using the guide that can be found in here

Install Paho Java via Maven

The Paho Java client library can be easily installed through the package management tool Maven. This is installed as follows:

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

Publishing a Message

MqttClient client = new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
client.connect();
MqttMessage message = new MqttMessage();
message.setPayload("Hello world from Java".getBytes());
client.publish("iot_data", message);
client.disconnect();

You have many other options, configurations that you can use when posting a message such as security, quality of service (QoS), and more; You can explore such options using the MQTT Java documentation.

Subscribing to receive messages

To receive messages you need to implement a Callback class in the Subscriber application as follows:

public class SimpleMqttCallBack implements MqttCallback {
 
  public void connectionLost(Throwable throwable) {
    System.out.println("Connection to MQTT broker lost!");
  }
 
  public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
    System.out.println("Message received:\n\t"+ new String(mqttMessage.getPayload()) );
  }
 
  public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
    // not used in this example
  }
}

The Callback is then used in the Subscriber application as follows:

MqttClient client=new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
client.setCallback( new SimpleMqttCallBack() );
client.connect();

Again, no further options are used (QoS, security) to connect the subscriber application to the MQTT broker. You can explore such options using the MQTT Java documentation.

Previous
Next