tencent cloud

DokumentasiTDMQ for MQTT

Dart SDK

Mode fokus
Ukuran font
Terakhir diperbarui: 2026-04-01 16:37:52

Feature Overview

The Dart/Flutter platform provides two main MQTT client libraries:

mqtt_client

The client library for the MQTT 3.1/3.1.1 protocol, compatible with Flutter, Dart VM, and Web platforms. It provides MqttServerClient and MqttBrowserClient for server-side and browser environments.

mqtt5_client

The client library specifically designed for the MQTT 5.0 protocol, providing full support for MQTT 5.0 features, including enhanced authentication, message properties, topic aliases, and more. It also supports both server and browser environments.

Cloud Resource Preparation

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

Environment Preparation

Selecting an Appropriate Client Library

Select a library based on the MQTT protocol version you need to use:
Using MQTT 3.1.1 (recommended for production environments)
dependencies:
mqtt_client: ^10.11.0

Using MQTT 5.0
dependencies:
mqtt5_client: ^4.15.2

Then run:
flutter pub get
# or
dart pub get

Sample Code

MQTT 5.0
MQTT 5.0 TLS
MQTT 3
MQTT 3 TLS

import 'dart:async';
import 'dart:convert';
import 'package:mqtt5_client/mqtt5_client.dart';
import 'package:mqtt5_client/mqtt5_server_client.dart';

Future<void> main() async {
// Obtain the access point from the MQTT console.
final server = 'mqtt-xxx.mqtt.tencenttdmq.com';
final port = 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.
final clientId = 'QuickStartMqtt5';

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

// Ensure that the first-level topic "home" has been created in the MQTT console.
final pubTopic = 'home/test';
final topicFilters = ['home/test', 'home/#', 'home/+'];
final qos = [MqttQos.atLeastOnce, MqttQos.atLeastOnce, MqttQos.atLeastOnce];

final total = 16;

final client = MqttServerClient.withPort(server, clientId, port);
client.logging(on: true);
client.keepAlivePeriod = 60;
client.autoReconnect = true;

// Set the connection message.
final connMessage = MqttConnectMessage()
.withClientIdentifier(clientId)
.authenticateAs(username, password)
.startClean();
client.connectionMessage = connMessage;

// Connection callback
client.onConnected = () {
print('Connected to $server');
// Subscribe
for (var i = 0; i < topicFilters.length; i++) {
client.subscribe(topicFilters[i], qos[i]);
print('Subscribed to topic ${topicFilters[i]} with QoS=${qos[i].index}');
}
};

client.onDisconnected = () {
print('Disconnected');
};

client.onAutoReconnect = () {
print('Auto reconnecting...');
};

client.onAutoReconnected = () {
print('Auto reconnected');
};

try {
print('Connecting to MQTT broker...');
await client.connect();
} catch (e) {
print('Exception: $e');
client.disconnect();
return;
}

if (client.connectionStatus!.state == MqttConnectionState.connected) {
print('MQTT client connected');

// Subscription message callback
client.updates?.listen((List<MqttReceivedMessage<MqttMessage>> c) {
final recMessage = c[0].payload as MqttPublishMessage;
final topic = c[0].topic;
final payload = recMessage.payload.message;
final content = payload != null ? utf8.decode(payload.toList()) : '';
print('Message arrived, topic=$topic, QoS=${recMessage.payload.header!.qos.index} content=[$content]');
});

// Publish a message.
for (var i = 0; i < total; i++) {
final builder = MqttPayloadBuilder();
builder.addString('Hello MQTT 5.0 - $i');
print('Prepare to publish message $i');
client.publishMessage(pubTopic, qos[0], builder.payload!);
print('Published message $i');
await Future.delayed(Duration(seconds: 3));
}

await Future.delayed(Duration(seconds: 3));
client.disconnect();
} else {
print('Connection failed - status is ${client.connectionStatus}');
client.disconnect();
}
}


import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:mqtt5_client/mqtt5_client.dart';
import 'package:mqtt5_client/mqtt5_server_client.dart';

Future<void> main() async {
// Obtain the access point from the MQTT console.
final server = 'mqtt-xxx.mqtt.tencenttdmq.com';
final port = 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.
final clientId = 'QuickStartMqtt5Tls';

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

// Ensure that the first-level topic "home" has been created in the MQTT console.
final pubTopic = 'home/test';
final topicFilters = ['home/test', 'home/#', 'home/+'];
final qos = [MqttQos.atLeastOnce, MqttQos.atLeastOnce, MqttQos.atLeastOnce];

final total = 16;

final client = MqttServerClient.withPort(server, clientId, port);
client.logging(on: true);
client.keepAlivePeriod = 60;
client.autoReconnect = true;
client.secure = true;

// Configure TLS/SSL.
SecurityContext context = SecurityContext.defaultContext;
client.securityContext = context;
client.onBadCertificate = (dynamic certificate) => true; // Used in the development environment; in the production environment, certificates should be verified.

// Set the connection message.
final connMessage = MqttConnectMessage()
.withClientIdentifier(clientId)
.authenticateAs(username, password)
.startClean();
client.connectionMessage = connMessage;

// Connection callback
client.onConnected = () {
print('Connected to $server');
// Subscribe
for (var i = 0; i < topicFilters.length; i++) {
client.subscribe(topicFilters[i], qos[i]);
print('Subscribed to topic ${topicFilters[i]} with QoS=${qos[i].index}');
}
};

client.onDisconnected = () {
print('Disconnected');
};

client.onAutoReconnect = () {
print('Auto reconnecting...');
};

client.onAutoReconnected = () {
print('Auto reconnected');
};

try {
print('Connecting to MQTT broker...');
await client.connect();
} catch (e) {
print('Exception: $e');
client.disconnect();
return;
}

if (client.connectionStatus!.state == MqttConnectionState.connected) {
print('MQTT client connected');

// Subscription message callback
client.updates?.listen((List<MqttReceivedMessage<MqttMessage>> c) {
final recMessage = c[0].payload as MqttPublishMessage;
final topic = c[0].topic;
final payload = recMessage.payload.message;
final content = payload != null ? utf8.decode(payload.toList()) : '';
print('Message arrived, topic=$topic, QoS=${recMessage.payload.header!.qos.index} content=[$content]');
});

// Publish a message.
for (var i = 0; i < total; i++) {
final builder = MqttPayloadBuilder();
builder.addString('Hello MQTT 5.0 TLS - $i');
print('Prepare to publish message $i');
client.publishMessage(pubTopic, qos[0], builder.payload!);
print('Published message $i');
await Future.delayed(Duration(seconds: 3));
}

await Future.delayed(Duration(seconds: 3));
client.disconnect();
} else {
print('Connection failed - status is ${client.connectionStatus}');
client.disconnect();
}
}


import 'dart:async';
import 'dart:convert';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

Future<void> main() async {
// Obtain 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.
final server = 'mqtt-xxx.mqtt.tencenttdmq.com';
final port = 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.
final clientId = 'QuickStart';

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

// Ensure that the first-level topic "home" has been created in the MQTT console.
final pubTopic = 'home/test';
final topicFilters = ['home/test', 'home/#', 'home/+'];
final qos = [MqttQos.atLeastOnce, MqttQos.atLeastOnce, MqttQos.atLeastOnce];

final total = 16;

final client = MqttServerClient.withPort(server, clientId, port);
client.logging(on: true);
client.setProtocolV311(); // Use the MQTT 3.1.1 protocol.
client.keepAlivePeriod = 60;
client.autoReconnect = true;
client.connectTimeoutPeriod = 3000;

// Set the connection message.
final connMessage = MqttConnectMessage()
.withClientIdentifier(clientId)
.authenticateAs(username, password)
.startClean()
.withWillQos(MqttQos.atLeastOnce);
client.connectionMessage = connMessage;

// Connection callback
client.onConnected = () {
print('Connected to $server');
// Subscribe
for (var i = 0; i < topicFilters.length; i++) {
client.subscribe(topicFilters[i], qos[i]);
print('Subscribed to topic ${topicFilters[i]} with QoS=${qos[i].index}');
}
};

client.onDisconnected = () {
print('Disconnected');
};

client.onAutoReconnect = () {
print('Auto reconnecting...');
};

client.onAutoReconnected = () {
print('Auto reconnected');
};

try {
print('Connecting to MQTT broker...');
await client.connect();
} catch (e) {
print('Exception: $e');
client.disconnect();
return;
}

if (client.connectionStatus!.state == MqttConnectionState.connected) {
print('MQTT client connected');

// Subscription message callback
client.updates?.listen((List<MqttReceivedMessage<MqttMessage>> c) {
final recMessage = c[0].payload as MqttPublishMessage;
final topic = c[0].topic;
final payload = recMessage.payload.message;
final content = payload != null ? utf8.decode(payload.toList()) : '';
print('Message arrived, topic=$topic, QoS=${recMessage.payload.header!.qos.index} content=[$content]');
});

// Publish a message.
for (var i = 0; i < total; i++) {
final builder = MqttClientPayloadBuilder();
builder.addString('Hello MQTT $i');
print('Prepare to publish message $i');
client.publishMessage(pubTopic, MqttQos.atLeastOnce, builder.payload!);
print('Published message $i');
await Future.delayed(Duration(seconds: 3));
}

await Future.delayed(Duration(seconds: 3));
client.disconnect();
} else {
print('Connection failed - status is ${client.connectionStatus}');
client.disconnect();
}
}




import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

Future<void> main() async {
// Obtain 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.
final server = 'mqtt-xxx.mqtt.tencenttdmq.com';
final port = 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.
final clientId = 'ClientQuickStartTls';

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

// Ensure that the first-level topic "home" has been created in the MQTT console.
final pubTopic = 'home/test';
final topicFilters = ['home/test', 'home/#', 'home/+'];
final qos = [MqttQos.atLeastOnce, MqttQos.atLeastOnce, MqttQos.atLeastOnce];

final total = 16;

final client = MqttServerClient.withPort(server, clientId, port);
client.logging(on: true);
client.setProtocolV311(); // Use the MQTT 3.1.1 protocol.
client.keepAlivePeriod = 60;
client.autoReconnect = true;
client.connectTimeoutPeriod = 3000;
client.secure = true;

// Configure TLS/SSL.
SecurityContext context = SecurityContext.defaultContext;
client.securityContext = context;
client.onBadCertificate = (dynamic certificate) => true; // Used in the development environment; in the production environment, certificates should be verified.

// Set the connection message.
final connMessage = MqttConnectMessage()
.withClientIdentifier(clientId)
.authenticateAs(username, password)
.startClean()
.withWillQos(MqttQos.atLeastOnce);
client.connectionMessage = connMessage;

// Connection callback
client.onConnected = () {
print('Connected to $server');
// Subscribe
for (var i = 0; i < topicFilters.length; i++) {
client.subscribe(topicFilters[i], qos[i]);
print('Subscribed to topic ${topicFilters[i]} with QoS=${qos[i].index}');
}
};

client.onDisconnected = () {
print('Disconnected');
};

client.onAutoReconnect = () {
print('Auto reconnecting...');
};

client.onAutoReconnected = () {
print('Auto reconnected');
};

try {
print('Connecting to MQTT broker...');
await client.connect();
} catch (e) {
print('Exception: $e');
client.disconnect();
return;
}

if (client.connectionStatus!.state == MqttConnectionState.connected) {
print('MQTT client connected');

// Subscription message callback
client.updates?.listen((List<MqttReceivedMessage<MqttMessage>> c) {
final recMessage = c[0].payload as MqttPublishMessage;
final topic = c[0].topic;
final payload = recMessage.payload.message;
final content = payload != null ? utf8.decode(payload.toList()) : '';
print('Message arrived, topic=$topic, QoS=${recMessage.payload.header!.qos.index} content=[$content]');
});

// Publish a message.
for (var i = 0; i < total; i++) {
final builder = MqttClientPayloadBuilder();
builder.addString('Hello MQTT $i');
print('Prepare to publish message $i');
client.publishMessage(pubTopic, MqttQos.atLeastOnce, builder.payload!);
print('Published message $i');
await Future.delayed(Duration(seconds: 3));
}

await Future.delayed(Duration(seconds: 3));
client.disconnect();
} else {
print('Connection failed - status is ${client.connectionStatus}');
client.disconnect();
}
}




Bantuan dan Dukungan

Apakah halaman ini membantu?

masukan