CloudAMQP with MQTT and Java Getting started

The by far best MQTT client for Java/JVM is Paho. Add the dependencys for the library or download the jar files and include them into the project. The following code snippet show how you can connect to a server and publish/subscribe a message. Check the webpage linked above for futher information.

ClientId is the unique MQTT client id to use for the device. If set to "" or None, the Paho library will generate a client id automatically.

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

public class MQTTSample {
  public static void main(String[] args) {
  String topic        = "CloudAMQP";
  String content      = "Hello CloudAMQP";
  int qos             = 1;
  String broker       = "tcp://CloudAMQP_server:CloudAMQP_port";

  //MQTT client id to use for the device. "" will generate a client id automatically
  String clientId     = "ClientId";

  MemoryPersistence persistence = new MemoryPersistence();
  try {
    MqttClient mqttClient = new MqttClient(broker, clientId, persistence);
    mqttClient.setCallback(new MqttCallback() {
      public void messageArrived(String topic, MqttMessage msg)
                throws Exception {
                    System.out.println("Recived:" + topic);
                    System.out.println("Recived:" + new String(msg.getPayload()));

      public void deliveryComplete(IMqttDeliveryToken arg0) {
                  System.out.println("Delivary complete");

      public void connectionLost(Throwable arg0) {
                  // TODO Auto-generated method stub

    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setPassword(new char[]{'p', 'a', 's', 's', 'w', 'r', 'd'});
    MqttMessage message = new MqttMessage(content.getBytes());
    System.out.println("Publish message: " + message);
    mqttClient.subscribe(topic, qos);
    mqttClient.publish(topic, message);
  } 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);