connectmq 1.0.0
connectmq: ^1.0.0 copied to clipboard
Publish and subscribe on the free public MQTT broker broker.connectmq.com in one line. TCP, TLS and WebSocket client for Dart and Flutter, plus a CLI.
example/main.dart
// Publish and subscribe on the free public broker broker.connectmq.com.
//
// Run with: dart run example/main.dart
//
// Everything on the public broker is readable by anyone. Use it for testing
// only; for production get a private broker at https://connectmq.com.
import 'package:connectmq/connectmq.dart';
Future<void> main() async {
// 1. Check connectivity (never throws).
final check = await testBroker();
print(check);
if (!check.ok) return;
// 2. Connect (TLS on native platforms, secure WebSocket on the web).
final client = await ConnectMQClient.connect();
print('Connected to ${client.url} as ${client.clientId}');
// 3. Use a random prefix so your topics do not collide with other users.
final prefix = topicPrefix(); // e.g. connectmq/demo/7f3a91
// 4. Subscribe with a wildcard and print every message.
final sub = client.subscribe('$prefix/sensors/+/temperature');
final listener = sub.listen((m) {
final data = m.json() as Map<String, Object?>;
print('${m.topic}: ${data['value']} °C (qos ${m.qos})');
});
await sub.ready;
// 5. Publish JSON (maps are encoded automatically). QoS 1 waits for PUBACK.
await client.publish('$prefix/sensors/kitchen/temperature', {
'value': 21.5,
}, qos: 1);
await client.publish('$prefix/sensors/garage/temperature', {'value': 14.0});
// 6. Retained messages are delivered to new subscribers.
final status = '$prefix/status';
await client.publish(status, 'online', qos: 1, retain: true);
final retained = await client.waitForMessage(status);
print(
'Retained on $status: ${retained.payload} (retain: ${retained.retain})',
);
await client.clearRetained(status); // clean up
await Future<void>.delayed(const Duration(seconds: 1));
await listener.cancel(); // unsubscribes on the broker
await client.close();
}