tencent cloud

TDMQ for MQTT

Java SDK

Focus Mode
Font Size
Last updated: 2026-04-01 16:37:52

Feature Overview

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

Cloud Resource Preparation

Please refer to resource creation operation steps to complete cloud resource preparation.

Environment Preparation

Installing Paho Java via Maven

MQTT 5 Paho SDK
MQTT 3.1.1 Paho SDK
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.mqttv5.client</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.5</version>
</dependency>

Example Code

MQTT 5
MQTT 5 TLS
MQTT 3.1.1
MQTT 3.1.1 TLS
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

import java.nio.ByteBuffer;
import org.eclipse.paho.mqttv5.client.IMqttToken;
import org.eclipse.paho.mqttv5.client.MqttCallback;
import org.eclipse.paho.mqttv5.client.MqttClient;
import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
import org.eclipse.paho.mqttv5.client.MqttDisconnectResponse;
import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.eclipse.paho.mqttv5.common.packet.MqttProperties;

public class QuickStart {
public static void main(String[] args) throws MqttException, InterruptedException {
// Get the access point from the MQTT console:
// For users implementing VPC connectivity via Private Link, use the private network access point.
// For users accessing over the public network, ensure the public network security policy permits access, and the machine running the program has public network connectivity.
String serverUri = "tcp://mqtt-xxx.mqtt.tencenttdmq.com:1883";

// A valid client identifier contains digits 0–9, lowercase letters a–z, and uppercase letters A–Z, with a total length of 1–23 characters.
// See https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901059.
String clientId = "QuickStart";

// In the console, on the Authentication tab, create an account and copy the username and password.
String username = "YOUR_USERNAME";
String password = "YOUR_PASSWORD";

// MQTT topic
String pubTopic = "home/test";
String[] topicFilters = new String[]{pubTopic, "home/#", "home/+"};
int[] qos = new int[]{1, 1, 1};

int total = 16;

MqttClient client = new MqttClient(serverUri, clientId, new MemoryPersistence());
client.setTimeToWait(3000);
MqttConnectionOptions options = new MqttConnectionOptions();
options.setUserName(username);
options.setPassword(password.getBytes(StandardCharsets.UTF_8));
options.setCleanStart(true);
options.setAutomaticReconnect(true);

client.setCallback(new MqttCallback() {
@Override
public void disconnected(MqttDisconnectResponse response) {
System.out.println("Disconnected: " + response.getReasonString());
}

@Override
public void mqttErrorOccurred(MqttException e) {
e.printStackTrace();
}

@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
byte[] payload = message.getPayload();
String content;
if (4 == payload.length) {
ByteBuffer buf = ByteBuffer.wrap(payload);
content = String.valueOf(buf.getInt());
} else {
content = new String(payload, StandardCharsets.UTF_8);
}
System.out.printf("Message arrived, topic=%s, QoS=%d content=[%s]%n",
topic, message.getQos(), content);
}

@Override
public void deliveryComplete(IMqttToken token) {

}

@Override
public void connectComplete(boolean reconnect, String serverURI) {
System.out.println(reconnect ? "Reconnected" : "Connected" + " to " + serverURI);
try {
// Subscribe
client.subscribe(topicFilters, qos);
} catch (MqttException e) {
e.printStackTrace();
}
}

@Override
public void authPacketArrived(int i, MqttProperties properties) {
}
});

client.connect(options);

for (int i = 0; i < total; i++) {
String msg = "Hello MQTT " + i;
MqttMessage message = new MqttMessage(msg.getBytes(StandardCharsets.UTF_8));
message.setQos(1);
System.out.printf("Prepare to publish message %d%n", i);
client.publish(pubTopic, message);
System.out.printf("Published message %d%n", i);
TimeUnit.SECONDS.sleep(3);
}
TimeUnit.SECONDS.sleep(3);

client.disconnect();
}
}
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import org.eclipse.paho.mqttv5.client.IMqttToken;
import org.eclipse.paho.mqttv5.client.MqttCallback;
import org.eclipse.paho.mqttv5.client.MqttClient;
import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
import org.eclipse.paho.mqttv5.client.MqttDisconnectResponse;
import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.eclipse.paho.mqttv5.common.packet.MqttProperties;
import org.eclipse.paho.mqttv5.common.packet.UserProperty;

public class QuickStartTls {

public static SSLSocketFactory buildSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, null, null);
return ctx.getSocketFactory();
}

public static void main(String[] args) throws Exception {
// Get the access point from the MQTT console:
// For users implementing VPC connectivity via Private Link, use the private network access point.
// For users accessing over the public network, ensure the public network security policy permits access, and the machine running the program has public network connectivity.
String serverUri = "ssl://mqtt-xxx.mqtt.tencenttdmq.com:8883";

// A valid client identifier contains digits 0–9, lowercase letters a–z, and uppercase letters A–Z, with a total length of 1–23 characters.
// See https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901059.
String clientId = "QuickStartTls";

// In the console, on the Authentication tab, create an account and copy the username and password.
String username = "YOUR_USERNAME";
String password = "YOUR_PASSWORD";

// MQTT topic
String topicName = "home/test";
String[] topicFilters = new String[]{topicName, "home/#", "home/+"};
int[] qos = new int[]{1, 1, 1};

int total = 16;

MqttClient client = new MqttClient(serverUri, clientId, new MemoryPersistence());
client.setTimeToWait(3000);
MqttConnectionOptions options = new MqttConnectionOptions();
options.setSocketFactory(buildSSLSocketFactory());
options.setHttpsHostnameVerificationEnabled(false);
options.setUserName(username);
options.setPassword(password.getBytes(StandardCharsets.UTF_8));
options.setCleanStart(true);
options.setAutomaticReconnect(true);

client.setCallback(new MqttCallback() {
@Override
public void disconnected(MqttDisconnectResponse response) {
System.out.println("Disconnected: " + response.getReasonString());
}

@Override
public void mqttErrorOccurred(MqttException e) {
e.printStackTrace();
}

@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
byte[] payload = message.getPayload();
String content;
if (4 == payload.length) {
ByteBuffer buf = ByteBuffer.wrap(payload);
content = String.valueOf(buf.getInt());
} else {
content = new String(payload, StandardCharsets.UTF_8);
}
System.out.printf("Message arrived, topic=%s, QoS=%d content=[%s]%n",
topic, message.getQos(), content);
}

@Override
public void deliveryComplete(IMqttToken token) {

}

@Override
public void connectComplete(boolean reconnect, String serverURI) {
System.out.println(reconnect ? "Reconnected" : "Connected" + " to " + serverURI);
try {
// Subscribe
IMqttToken token = client.subscribe(topicFilters, qos);
int[] reasonCodes = token.getReasonCodes();
for (int i = 0; i < reasonCodes.length; i++) {
System.out.printf("Subscribed to topic %s with QoS=%d, Granted-QoS: %d%n",
topicFilters[i], qos[i], reasonCodes[i]);
}

if (token.isComplete()) {
List<UserProperty> userProperties = token.getResponseProperties().getUserProperties();
printUserProperties(userProperties);
}
} catch (MqttException e) {
e.printStackTrace();
}
}

@Override
public void authPacketArrived(int i, MqttProperties properties) {
}
});

client.connect(options);

for (int i = 0; i < total; i++) {
String msg = "Hello MQTT " + i;
MqttMessage message = new MqttMessage(msg.getBytes(StandardCharsets.UTF_8));
message.setQos(1);
System.out.printf("Prepare to publish message %d%n", i);
client.publish(topicName, message);
System.out.printf("Published message %d%n", i);
TimeUnit.SECONDS.sleep(3);
}
TimeUnit.SECONDS.sleep(3);

client.disconnect();
}

static void printUserProperties(List<UserProperty> userProperties) {
if (null != userProperties) {
for (UserProperty userProperty : userProperties) {
System.out.printf("User property: %s = %s%n", userProperty.getKey(), userProperty.getValue());
}
}
}
}


import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
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 QuickStart {
public static void main(String[] args) throws MqttException, InterruptedException {
// Get the access point from the MQTT console:
// For users implementing VPC connectivity via Private Link, use the private network access point.
// For users accessing over the public network, ensure the public network security policy permits access, and the machine running the program has public network connectivity.
String serverUri = "tcp://mqtt-xxx.mqtt.tencenttdmq.com:1883";

// A valid client identifier contains digits 0–9, lowercase letters a–z, and uppercase letters A–Z, with a total length of 1–23 characters.
// See https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901059.
String clientId = "QuickStart";

// In the console, on the Authentication tab, create an account and copy the username and password.
String username = "YOUR_USERNAME";
String password = "YOUR_PASSWORD";

// Ensure that the first-level topic "home" has been created in the MQTT console.
String pubTopic = "home/test";
String[] topicFilters = new String[]{pubTopic, "home/#", "home/+"};
int[] qos = new int[]{1, 1, 1};

int total = 16;

try (MqttClient client = new MqttClient(serverUri, clientId, new MemoryPersistence())) {
client.setTimeToWait(3000);
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(username);
options.setPassword(password.toCharArray());
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
options.setCleanSession(true);
options.setAutomaticReconnect(true);

MqttCallback callback = new MqttCallback(client, topicFilters, qos);
client.setCallback(callback);

client.connect(options);

for (int i = 0; i < total; i++) {
String msg = "Hello MQTT " + i;
MqttMessage message = new MqttMessage(msg.getBytes(StandardCharsets.UTF_8));
message.setQos(1);
System.out.printf("Prepare to publish message %d%n", i);
client.publish(pubTopic, message);
System.out.printf("Published message %d%n", i);
TimeUnit.SECONDS.sleep(3);
}
TimeUnit.SECONDS.sleep(3);

client.disconnect();
}
}

static class MqttCallback implements MqttCallbackExtended {

private final MqttClient client;

private final String[] topicFilters;
private final int[] qos;

public MqttCallback(MqttClient client, String[] topicFilters, int[] qos) {
this.client = client;
this.topicFilters = topicFilters;
this.qos = qos;
}

public void messageArrived(String topic, MqttMessage message) {
System.out.printf("Message arrived, topic=%s, QoS=%d, Dup=%s, Retained=%s, content=[%s]%n",
topic, message.getQos(), message.isDuplicate(), message.isRetained(),
new String(message.getPayload(), StandardCharsets.UTF_8));
}

public void connectionLost(Throwable cause) {
System.out.println("connectionLost: " + cause.getMessage());
}

@Override
public void connectComplete(boolean reconnect, String serverURI) {
System.out.println(reconnect ? "Reconnected" : "Connected" + " to " + serverURI);
try {
client.subscribe(topicFilters, qos);
System.out.printf("Subscribed %d topics%n", topicFilters.length);
} catch (MqttException e) {
e.printStackTrace();
}
}

public void deliveryComplete(IMqttDeliveryToken token) {
System.out.printf("Delivery completed: packet-id=%d%n", token.getMessageId());
}
}
}
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
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;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

public class QuickStartTls {

public static SSLSocketFactory buildSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, null, null);
return ctx.getSocketFactory();
}

public static void main(String[] args) throws MqttException, InterruptedException, NoSuchAlgorithmException, KeyManagementException {

// Get the access point from the MQTT console:
// For users implementing VPC connectivity via Private Link, use the private network access point.
// For users accessing over the public network, ensure the public network security policy permits access, and the machine running the program has public network connectivity.
String serverUri = "ssl://mqtt-xxxx.mqtt.tencenttdmq.com:8883";
// A valid client identifier contains digits 0–9, lowercase letters a–z, and uppercase letters A–Z, with a total length of 1–23 characters.
// See https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901059.
String clientId = "ClientQuickStartTls";

// In the console, on the Authentication tab, create an account and copy the username and password.
String username = "YOUR_USERNAME";
String password = "YOUR_PASSWORD";

// Ensure that the first-level topic "home" has been created in the MQTT console.
String topic = "home/test";

String[] topicFilters = new String[]{"home/test"};
int[] qos = new int[]{1};

int total = 16;

try (MqttClient client = new MqttClient(serverUri, clientId, new MemoryPersistence())) {
client.setTimeToWait(3000);
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(username);
options.setPassword(password.toCharArray());
options.setSocketFactory(buildSSLSocketFactory());
options.setHttpsHostnameVerificationEnabled(false);
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
options.setCleanSession(true);
options.setAutomaticReconnect(true);
client.connect(options);

client.setCallback(new MqttCallback(client, topicFilters, qos));

for (int i = 0; i < total; i++) {
String msg = "Hello MQTT " + i;
MqttMessage message = new MqttMessage(msg.getBytes());
message.setQos(1);
System.out.printf("Prepare to publish message %d%n", i);
client.publish(topic, message);
System.out.printf("Published message %d%n", i);
TimeUnit.SECONDS.sleep(1);
}

TimeUnit.SECONDS.sleep(3);

client.disconnect();
}
}

static class MqttCallback implements MqttCallbackExtended {

private final MqttClient client;

private final String[] topicFilters;
private final int[] qos;

public MqttCallback(MqttClient client, String[] topicFilters, int[] qos) {
this.client = client;
this.topicFilters = topicFilters;
this.qos = qos;
}

public void messageArrived(String topic, MqttMessage message) {
System.out.printf("Message arrived, topic=%s, QoS=%d content=[%s]%n", topic, message.getQos(),
new String(message.getPayload(), StandardCharsets.UTF_8));
}

public void connectionLost(Throwable cause) {
System.out.println("connectionLost: " + cause.getMessage());
}

@Override
public void connectComplete(boolean reconnect, String serverURI) {
System.out.println(reconnect ? "Reconnected" : "Connect" + serverURI);
try {
client.subscribe(topicFilters, qos);
System.out.printf("Subscribed %d topics%n", topicFilters.length);
} catch (MqttException e) {
e.printStackTrace();
}
}

public void deliveryComplete(IMqttDeliveryToken token) {
System.out.printf("Delivery completed: packet-id=%d%n", token.getMessageId());
}
}
}
Parameter
Description
pubTopic
Target topic for the message to be published.
Message topics can contain multiple levels, separated by forward slashes (/). The first-level topic needs to be created on the Topic tab in the console. For details, refer to Topic Names and Topic Filters.
topicFilters
One or more subscription expressions.
Subscription expressions can contain wildcards. For details, refer to Topic Names and Topic Filters.
qos
QoS array. The array length must match the number of topic filter elements.
The most commonly used QoS is 1, which is At-Least-Once delivery. For details, refer to Quality of Service Levels and Protocol Flows.
serverUri
Access point of the MQTT instance, which can be copied from the Basic Information > Access Information section of the target cluster in the console, as shown below.
Standard access point: tcp://mqtt-xxx.mqtt.tencenttdmq.com:1883
TLS access point: ssl://mqtt-xxx.mqtt.tencenttdmq.com:8883
Standard WebSocket access point: ws://mqtt-xxx.mqtt.tencenttdmq.com:80/mqtt
TLS WebSocket access point: wss://mqtt-xxx.mqtt.tencenttdmq.com:443/mqtt



clientId
Unique identifier of the device, such as vehicle identification number (VIN) and product serial number.
A valid client identifier contains digits 0–9, lowercase letters a–z, and uppercase letters A–Z, with a total length of 1–23 characters. For details, refer to Client Identifier.
username
Connection username, which can be copied from the Authentication Management page on the cluster details page in the console.



password
Password matching the connection username, which can be copied from the Authentication Management page on the cluster details page in the console.



Help and Support

Was this page helpful?

Help us improve! Rate your documentation experience in 5 mins.

Feedback