Establishing the connection
With your orchestrator initialized and aware of how and where to connect, you are ready to open the active session with the broker.
To do this, you will use the OpenConnectionAsync method.
Opening the connection
Section titled “Opening the connection”The OpenConnectionAsync method returns a GenericResult<bool>. This result object tells you if the connection was successful or, if it failed, provides the exact error code and description returned by the broker.
using System.Threading;using SyMqtt;
// Open the connection activelyvar connectionResult = await mqttBox.OpenConnectionAsync(CancellationToken.None);
if (connectionResult.Success){ Console.WriteLine("Successfully connected to the broker!");}else{ Console.WriteLine($"Connection failed! Error {connectionResult.ErrorCode}: {connectionResult.ErrorDescription}");}What happens under the hood
Section titled “What happens under the hood”When you call OpenConnectionAsync, SyMqttBox automates several critical operations:
- Topology Freeze: The moment the connection opens, your topology is frozen. You can no longer add or remove topics or channels. If you need to reconfigure your setup, you must close the connection first.
- Automatic Subscription: The box automatically iterates through all your registered channels and receiver topic holders and subscribes to their respective MQTT topics on the broker in a single, efficient pass.
- Session Cache: If the connection drops unexpectedly, a safe snapshot of your channels remains active in memory to guarantee immediate routing recovery upon reconnection.
Automatic reconnection
Section titled “Automatic reconnection”By default, the AutoReconnect property is set to true. If a network disruption occurs or the broker drops the session, SyMqttBox enters a specialized recovery loop:
- It completely avoids blocking your main application threads.
- It safely attempts to reconnect every few seconds using an internal retry mechanism.
- During the disconnection window, the internal channel map is safely cleared to prevent stale routing, and it is instantly restored the millisecond the handshake succeeds again.
If you intentionally want to disconnect and stop the automatic retry loop (for instance, to shut down your application or change configuration parameters), you must use the explicit close method CloseConnectionAsync:
// Closes the connection gracefully and safely halts the auto-reconnect loopvar disconnectResult = await mqttBox.CloseConnectionAsync();if (!disconnectResult.Success){ Console.WriteLine($"Graceful disconnect failed: {disconnectResult.ErrorDescription}");}Now that your connection is up and running, you can start transferring data through your infrastructure.
Let’s move to the next step to see how to use the core communication methods for sending and fetching messages.