dependencies:mqtt_client: ^10.11.0
dependencies:mqtt5_client: ^4.15.2
flutter pub get# ordart pub get
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 consolefinal 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 charactersfinal clientId = 'QuickStartMqtt5';// On the console --> Authentication Tab page, create an account and copy the username and passwordfinal username = 'YOUR_USERNAME';final password = 'YOUR_PASSWORD';// Confirm that the first-level topic "home" has been created in the MQTT consolefinal 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 messagefinal connMessage = MqttConnectMessage().withClientIdentifier(clientId).authenticateAs(username, password).startClean();client.connectionMessage = connMessage;// Connection callbackclient.onConnected = () {print('Connected to $server');// Subscribefor (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');// Subscribe message callbackclient.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 messagefor (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 consolefinal 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 charactersfinal clientId = 'QuickStartMqtt5Tls';// On the console --> Authentication Tab page, create an account and copy the username and passwordfinal username = 'YOUR_USERNAME';final password = 'YOUR_PASSWORD';// Confirm that the first-level topic "home" has been created in the MQTT consolefinal 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/SSLSecurityContext context = SecurityContext.defaultContext;client.securityContext = context;client.onBadCertificate = (dynamic certificate) => true; // Used in development environments; in production environments, certificates should be verified// Set the connection messagefinal connMessage = MqttConnectMessage().withClientIdentifier(clientId).authenticateAs(username, password).startClean();client.connectionMessage = connMessage;// Connection callbackclient.onConnected = () {print('Connected to $server');// Subscribefor (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');// Subscribe message callbackclient.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 messagefor (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:// Users who have implemented VPC network 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// Refer to https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901059final clientId = 'QuickStart';// On the console --> Authentication Tab page, create an account and copy the username and passwordfinal username = 'YOUR_USERNAME';final password = 'YOUR_PASSWORD';// Confirm that the first-level topic "home" has been created in the MQTT consolefinal 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 protocolclient.keepAlivePeriod = 60;client.autoReconnect = true;client.connectTimeoutPeriod = 3000;// Set the connection messagefinal connMessage = MqttConnectMessage().withClientIdentifier(clientId).authenticateAs(username, password).startClean().withWillQos(MqttQos.atLeastOnce);client.connectionMessage = connMessage;// Connection callbackclient.onConnected = () {print('Connected to $server');// Subscribefor (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');// Subscribe message callbackclient.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 messagefor (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:// Users who have implemented VPC network 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// Refer to https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901059final clientId = 'ClientQuickStartTls';// On the console --> Authentication Tab page, create an account and copy the username and passwordfinal username = 'YOUR_USERNAME';final password = 'YOUR_PASSWORD';// Confirm that the first-level topic "home" has been created in the MQTT consolefinal 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 protocolclient.keepAlivePeriod = 60;client.autoReconnect = true;client.connectTimeoutPeriod = 3000;client.secure = true;// Configure TLS/SSLSecurityContext context = SecurityContext.defaultContext;client.securityContext = context;client.onBadCertificate = (dynamic certificate) => true; // Used in development environments; in production environments, certificates should be verified// Set the connection messagefinal connMessage = MqttConnectMessage().withClientIdentifier(clientId).authenticateAs(username, password).startClean().withWillQos(MqttQos.atLeastOnce);client.connectionMessage = connMessage;// Connection callbackclient.onConnected = () {print('Connected to $server');// Subscribefor (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');// Subscribe message callbackclient.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 messagefor (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();}}
Feedback