Skip to content

Java ​

Use the Eclipse Paho Java client to connect Java 8+ applications and services to ConnectMQ over TLS.

How it connects ​

Java application connecting to ConnectMQ A Java application uses Eclipse Paho Java client · Java 8+ to connect to broker.connectmq.com over MQTT · TLS 8883 with a username, password and a client ID based on the issued client ID. The broker checks the client with the Broker API (credentials, client ID, ACL and plan limits) and delivers messages to the web console and other devices and services. Your codeEveryone else on the brokerConnectMQ CloudMQTT · TLS 8883username · password · client ID <ISSUED_ID>_<suffix>authJava applicationEclipse Paho Java client · Java 8+client.publish(TOPIC, payload, 1, false);ssl://broker.connectmq.com:8883 · resubscribe after a reconnectMQTT brokerbroker.connectmq.comTLS 8883 · WSS 8084 /mqtt · MQTT 3.1.1 and 5Broker APICredentials · client IDACL · plan limitsWeb consoleapp.connectmq.com · live topics · alertsDevices & servicesESP32 · ConnectMQ Edge · back ends · appsMQTT messagesConnection check (credentials, client ID, ACL)

Install ​

xml
<dependency>
  <groupId>org.eclipse.paho</groupId>
  <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
  <version>1.2.5</version>
</dependency>
kotlin
implementation("org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5")

Publish and subscribe ​

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

import java.nio.charset.StandardCharsets;

public class Example {
    static final String FILTER = "acme/istanbul/#";
    static final String TOPIC = "acme/istanbul/assembly/line1/java-01/telemetry";

    public static void main(String[] args) throws Exception {
        String clientId = System.getenv("CMQ_CLIENT_ID") + "_java-service"; // issued client ID + "_" + suffix

        MqttAsyncClient client = new MqttAsyncClient(
                "ssl://broker.connectmq.com:8883", clientId, new MemoryPersistence());

        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(System.getenv("CMQ_USERNAME"));
        options.setPassword(System.getenv("CMQ_PASSWORD").toCharArray());
        options.setKeepAliveInterval(60);
        options.setCleanSession(true);
        options.setAutomaticReconnect(true); // reconnect if the connection drops

        client.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverUri) {
                // Runs after the first connect and after every reconnect:
                // a clean session has no subscriptions, so subscribe here
                try {
                    client.subscribe(FILTER, 1);
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) {
                System.out.println(topic + ": " + new String(message.getPayload(), StandardCharsets.UTF_8));
            }

            @Override
            public void connectionLost(Throwable cause) {
                System.out.println("Connection lost, reconnecting: " + cause.getMessage());
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) { }
        });

        client.connect(options).waitForCompletion();

        while (true) {
            if (client.isConnected()) {
                byte[] payload = "{\"temperature\":21.5}".getBytes(StandardCharsets.UTF_8);
                client.publish(TOPIC, payload, 1, false);
            }
            Thread.sleep(5000);
        }
    }
}
bash
# Java 11+, with the Paho jar on the class path
CMQ_CLIENT_ID=connectmq_client_123456 CMQ_USERNAME=cmq_xxxx CMQ_PASSWORD='...' \
  java -cp org.eclipse.paho.client.mqttv3-1.2.5.jar Example.java

ssl:// uses the JVM's trusted CAs to verify the broker certificate, so you do not need a keystore (Java 8u141 or later). The Paho v3 client speaks MQTT 3.1.1.

Use your issued client ID

MqttClient.generateClientId() creates a random ID that your private broker refuses with Client identifier not valid (0x85). Use your issued client ID plus a suffix that is unique per process (why).

Notes ​

  • connectComplete runs after every reconnect. Subscribing there keeps subscriptions alive, because a clean session starts without any.
  • Use MqttAsyncClient as above, or MqttClient for simple scripts. Do not call blocking MqttClient methods inside messageArrived.
  • Send JSON objects such as {"temperature": 21.5}: the console turns every numeric field into a live value with a sparkline. A JSON library such as Jackson or Gson can build the payload.
  • Try without an account: connect to tcp://broker.connectmq.com:1883 with no username or password. The public test broker is readable by anyone, so use it for experiments only.

Fully managed MQTT broker for connected devices.