connectmq

Publish and subscribe on the free public MQTT broker broker.connectmq.com from Dart and Flutter in a few lines. A thin, preconfigured wrapper around mqtt_client for TCP, TLS, WebSocket and secure WebSocket, plus a small CLI. It also works with private brokers created on connectmq.com.

final client = await ConnectMQClient.connect();
client.subscribe('connectmq/demo/7f3a91/#').listen((m) => print(m.payload));
await client.publish('connectmq/demo/7f3a91/temp', {'value': 21.5});

Works on Android, iOS, macOS, Windows, Linux, the Dart VM / server, and the web (Flutter web, dart2js and dart2wasm; browsers use WebSocket only).

Install

dart pub add connectmq      # Dart
flutter pub add connectmq   # Flutter

Quick start

import 'package:connectmq/connectmq.dart';

Future<void> main() async {
  // TLS on native platforms, secure WebSocket on the web.
  final client = await ConnectMQClient.connect();

  // The public broker is shared: use a random prefix such as connectmq/demo/7f3a91.
  final topic = '${topicPrefix()}/hello';

  final sub = client.subscribe(topic);
  sub.listen((m) => print('${m.topic}: ${m.payload}'));
  await sub.ready; // broker acknowledged the subscription

  await client.publish(topic, 'Hello from Dart');            // String -> UTF-8
  await client.publish(topic, {'temp': 21.5}, qos: 1);       // Map -> JSON, waits for PUBACK

  // Wait for a single message (retained messages count).
  final last = await client.waitForMessage(topic, timeout: Duration(seconds: 5));
  print(last.json());

  await client.close();
}

Check connectivity without throwing:

final result = await testBroker(transport: MqttTransport.wss);
print(result); // OK  wss://broker.connectmq.com:8084/mqtt  connect 250 ms, round-trip 32 ms

Flutter

subscribe() returns a Stream, so it plugs straight into a StreamBuilder:

import 'package:connectmq/connectmq.dart';
import 'package:flutter/material.dart';

class Temperature extends StatefulWidget {
  const Temperature({super.key, required this.client, required this.topic});

  final ConnectMQClient client;
  final String topic;

  @override
  State<Temperature> createState() => _TemperatureState();
}

class _TemperatureState extends State<Temperature> {
  // Create the stream once (not in build), it is single-subscription.
  late final Stream<ConnectMQMessage> _messages =
      widget.client.subscribe(widget.topic);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<ConnectMQMessage>(
      stream: _messages,
      builder: (context, snapshot) {
        if (snapshot.hasError) return Text('Error: ${snapshot.error}');
        if (!snapshot.hasData) return const CircularProgressIndicator();
        final data = snapshot.data!.json() as Map<String, dynamic>;
        return Text('${data['value']} °C');
      },
    );
  }
}

When the widget is disposed, StreamBuilder cancels its listener and the topic is unsubscribed on the broker. Create the ConnectMQClient once (for example in your app state) and call close() when you no longer need it.

Platforms: Android, iOS and desktop use MqttServerClient (all four transports). Flutter web uses MqttBrowserClient and supports only ws and wss (the default there is wss); tcp/tls throw a ConnectMQException in the browser. Android apps need the INTERNET permission, and macOS apps the com.apple.security.network.client entitlement.

API

Top-level

Member Description
brokerHost 'broker.connectmq.com'
MqttTransport tcp, tls, ws, wss (with scheme, defaultPort, path, MqttTransport.parse('wss'))
defaultTransport MqttTransport.tls (native) or MqttTransport.wss (web)
brokerUrl(transport, {host, port}) e.g. mqtts://broker.connectmq.com:8883, wss://broker.connectmq.com:8084/mqtt
topicPrefix([root = 'connectmq/demo']) Random prefix such as connectmq/demo/7f3a91
topicMatches(filter, topic) MQTT filter matching with +, # and $share/{group}/
testBroker({transport, host, port, username, password, timeout}) Connect + round-trip check, returns BrokerTestResult (ok, url, connectTime, roundTripTime, error). Never throws.
brokerInfo Endpoints and limits of the public broker (toJson())
encodePayload(value) The payload encoding used by publish

ConnectMQClient

Member Description
ConnectMQClient.connect({...}) Connects and returns a connected client (throws ConnectMQException on failure)
publish(topic, payload, {qos = 0, retain = false, timeout}) String as UTF-8, List<int>/Uint8List as raw bytes, null as empty, anything else as JSON. QoS 1/2 complete when the broker acknowledges.
clearRetained(topic) Publishes an empty retained message, which deletes the retained message
subscribe(filter, {qos = 0}) Returns a ConnectMQSubscription (a Stream<ConnectMQMessage> with ready and filter)
unsubscribe(filter) Unsubscribes and closes all streams of the filter
waitForMessage(filter, {timeout = 30 s, qos}) Next matching message (or the retained one); throws TimeoutException
close() Disconnects and closes all subscription streams
isConnected, done Connection state; done completes when the connection is closed or lost
url, transport, clientId Connection details
mqttClient The underlying mqtt_client MqttClient for advanced use

Subscription behaviour:

  • The SUBSCRIBE is sent immediately. Messages are buffered until you listen, so retained messages that arrive right after the SUBACK are never lost.
  • When the stream's listener cancels, the filter is unsubscribed on the broker (unless another stream for the same filter is still listening).
  • If the broker rejects the subscription or the connection drops, the stream emits a ConnectMQException and closes.
  • Streams are single-subscription; call .asBroadcastStream() if you need several listeners.

ConnectMQMessage

Member Description
topic Topic the message was published to
payload Payload decoded as UTF-8 String
bytes Raw payload Uint8List
json() Payload decoded as JSON
qos 0, 1 or 2
retain true for retained messages delivered on subscribe
received Local receive time

Connect options

Option Default Description
transport tls (wss on the web) MqttTransport.tcp, .tls, .ws or .wss
host broker.connectmq.com Broker host name
port per transport (1883, 8883, 8083, 8084) Broker port
clientId 'dart-' + random Must be non-empty and unique
username, password none Credentials (private brokers)
keepAlive 60 s MQTT keep alive interval
timeout 10 s Connect timeout, also the QoS 1/2 acknowledgement timeout
cleanSession true Start with a clean session

The client speaks MQTT 3.1.1 and does not reconnect automatically: listen to done and connect again if you need to.

Private broker

For production, create a private broker with its own credentials at connectmq.com and pass its host and credentials:

final client = await ConnectMQClient.connect(
  host: 'your-broker.connectmq.com',
  username: 'device-1',
  password: const String.fromEnvironment('MQTT_PASSWORD'),
);
await client.publish('factory/line1/status', {'running': true}, qos: 1, retain: true);

CLI

dart pub global activate connectmq

connectmq test                 # OK  mqtts://broker.connectmq.com:8883  connect 323 ms, round-trip 49 ms
connectmq test -t wss
connectmq info                 # endpoints and limits as JSON
connectmq prefix               # connectmq/demo/7f3a91
connectmq sub "connectmq/demo/7f3a91/#" --json
connectmq pub connectmq/demo/7f3a91/temp '{"value":21.5}' -q 1 -r
echo hello | connectmq pub connectmq/demo/7f3a91/text
Option Description
-t, --transport tcp, tls (default), ws, wss
-H, --host, -P, --port Broker host and port (default broker.connectmq.com)
-q, --qos QoS 0, 1 or 2
-r, --retain Publish as retained message
-n, --count Exit after n messages (sub)
-j, --json Print messages as JSON lines (sub, test)
-u, --username, -p, --password Credentials for private brokers

Public broker

Protocol URL
MQTT (TCP) mqtt://broker.connectmq.com:1883
MQTT over TLS mqtts://broker.connectmq.com:8883
WebSocket ws://broker.connectmq.com:8083/mqtt
Secure WebSocket wss://broker.connectmq.com:8084/mqtt

Access is anonymous, but the client ID must be non-empty and unique. The TLS certificate is issued by Let's Encrypt and verified with the system CAs.

Limit Value
Message size 64 KB
Publish rate 10 messages per second per client
Subscriptions 10 per client
Topic depth 8 levels
QoS 0, 1 and 2
Retained messages yes
Wildcards + and #
Shared subscriptions $share/{group}/{filter}
Session expiry up to 30 minutes

Everything on the public broker is public. Any client can subscribe to # and read your messages. Use it for testing only, put your topics below a random prefix (topicPrefix()), and never send personal data or secrets. For production, create a private broker with its own credentials at connectmq.com.

More: Free Public MQTT Broker for Testing.

Other languages

The same API is available for:

License

MIT

Libraries

connectmq
Publish and subscribe on the free public MQTT broker broker.connectmq.com from Dart and Flutter.