tencent cloud

TDMQ for MQTT

Related Agreement
개인 정보 보호 정책
데이터 개인 정보 보호 및 보안 계약
문서TDMQ for MQTT

Step 3: Using the SDK to Send and Receive Messages

포커스 모드
폰트 크기
마지막 업데이트 시간: 2026-04-01 16:24:56
After completing configurations of resources, such as clusters and user permissions, in the console, you can use the SDK demo we provide to connect to the cluster and perform message sending and receiving tests. This document uses the Java SDK as an example to show how to send and receive messages over the public network, so as to help you better understand the complete process of sending and receiving messages.

Prerequisites

You have created TDMQ for MQTT cluster resources.
You have completed the environment configuration by following Preparations.

Operation Steps

2. Extract the downloaded demo package and go to the src/***/tdmq/mqtt/example directory.
3. Configure the parameters of the message sending and receiving program QuickStart.java. Here, the simple message sending and receiving program under the paho/v5 directory is used as an example.
package com.tencent.tdmq.mqtt.example.paho.v5;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;
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 SubscriberQuickStart {

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 = "SubscriberQuickStart";

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

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

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) {
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);
List<UserProperty> userProperties = message.getProperties().getUserProperties();
printUserProperties(userProperties);
}

@Override
public void deliveryComplete(IMqttToken token) {
System.out.println("Delivery complete for packet-id: " + token.getMessageId());
}

@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) {
System.out.println("Received auth packet with id: " + i);
}
});

client.connect(options);
TimeUnit.MINUTES.sleep(5);

client.disconnect();

client.close();
}

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());
}
}
}
}
Note:
All the following parameters can be obtained from the TDMQ for MQTT console.
Parameter
Description
serverUri
The Broker connection address can be copied from the Access Information module on the Basic Information page of the target cluster in the console. Here, use the public network access point with the following format: tcp://mqtt-xxxxx-nj-public.mqtt.tencenttdmq.com:1883

username
Username for the connection. Copy it from the Authentication Management page of the cluster in the console.
password
Password for the username. Copy it from the Authentication Management page of the cluster in the console.

topicName
Fill in the topic name. The first-level topic must be created in advance in the console. You can customize the second-level topic name.
4. Compile and run the producer program PublisherQuickStart.java. The results are shown below:
Connected to tcp://mqtt-xxx.mqtt.tencenttdmq.com:1883
Subscribed to topic home/test with QoS=1, Granted-QoS: 1
Subscribed to topic home/# with QoS=1, Granted-QoS: 1
Subscribed to topic home/+ with QoS=1, Granted-QoS: 1

Prepare to publish message 0
Published message 0
Message arrived, topic=home/test, QoS=1 content=[Hello MQTT 0]

Prepare to publish message 1
Published message 1
Message arrived, topic=home/test, QoS=1 content=[Hello MQTT 1]

Prepare to publish message 2
Published message 2
Message arrived, topic=home/test, QoS=1 content=[Hello MQTT 2]

[... Intermediate messages omitted ...]

Prepare to publish message 14
Published message 14
Message arrived, topic=home/test, QoS=1 content=[Hello MQTT 14]

Prepare to publish message 15
Published message 15
Message arrived, topic=home/test, QoS=1 content=[Hello MQTT 15]

Disconnected: Normal disconnection


도움말 및 지원

문제 해결에 도움이 되었나요?

피드백