Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor: Handling Reconnections #153

Merged
merged 3 commits into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 32 additions & 22 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -1,27 +1,37 @@
{
"version": "0.2.0",
"configurations": [

{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/Tests/HiveMQtt.Test/bin/Debug/net8.0/HiveMQtt.Test.dll",
"args": [],
"cwd": "${workspaceFolder}/Tests/HiveMQtt.Test",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "integratedTerminal",
"stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
}
{
"name": "SendMessageOnLoop .NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build SendMessageOnLoop",
"program": "${workspaceFolder}/Examples/SendMessageOnLoop/bin/Debug/net8.0/SendMessageOnLoop.dll",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
"console": "internalConsole"
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
},
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/Tests/HiveMQtt.Test/bin/Debug/net8.0/HiveMQtt.Test.dll",
"args": [],
"cwd": "${workspaceFolder}/Tests/HiveMQtt.Test",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "integratedTerminal",
"stopAtEntry": false
}
]
}
19 changes: 15 additions & 4 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile",
"group": {
"kind": "build",
"isDefault": true
}
},
{
"label": "build SendMessageOnLoop",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/Examples/SendMessageOnLoop/SendMessageOnLoop.csproj",
],
"problemMatcher": "$msCompile",
"group": "build"
},
{
Expand Down Expand Up @@ -80,10 +94,7 @@
"${workspaceFolder}/Examples/SubscriberWithEvents/SubscriberWithEvents.csproj"
],
"problemMatcher": "$msCompile",
"group": {
"kind": "build",
"isDefault": true
}
"group": "build"
}
]
}
9 changes: 2 additions & 7 deletions Examples/Reconnect/Reconnect.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,12 @@
<Nullable>enable</Nullable>
</PropertyGroup>

<!-- Use the HiveMQtt project as a local source. Otherwise, fetch from nuget. -->
<PropertyGroup>
<RestoreSources>$(RestoreSources);../../Source/HiveMQtt/bin/Debug/;https://api.nuget.org/v3/index.json</RestoreSources>
</PropertyGroup>

<!-- Update the version to match -->
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<WarningLevel>4</WarningLevel>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="HiveMQtt" Version="0.11.1" />
<ProjectReference Include="..\..\Source\HiveMQtt\HiveMQtt.csproj" />
</ItemGroup>

<ItemGroup>
Expand Down
116 changes: 94 additions & 22 deletions Examples/SendMessageOnLoop/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using HiveMQtt.Client;
using HiveMQtt.Client.Options;
using HiveMQtt.MQTT5.Types;
using HiveMQtt.Client.Exceptions;

// Connect to localhost:1883. Change for brokers elsewhere.
// Run HiveMQ CE locally: docker run --name hivemq-ce -d -p 1883:1883 hivemq/hivemq-ce
Expand All @@ -17,6 +18,78 @@

var client = new HiveMQClient(options);


// This handler is called when the client is disconnected
client.AfterDisconnect += async (sender, args) =>
{
var client = (HiveMQClient)sender;

Console.WriteLine($"AfterDisconnect Handler called with args.CleanDisconnect={args.CleanDisconnect}.");

// We've been disconnected
if (args.CleanDisconnect)
{
Console.WriteLine("--> AfterDisconnectEventArgs indicate a clean disconnect.");
Console.WriteLine("--> A clean disconnect was requested by either the client or the broker.");
}
else
{
Console.WriteLine("--> AfterDisconnectEventArgs indicate an unexpected disconnect.");
Console.WriteLine("--> This could be due to a network outage, broker outage, or other issue.");
Console.WriteLine("--> In this case we will attempt to reconnect periodically.");

// We could have been disconnected for any number of reasons: network outage, broker outage, etc.
// Here we loop with a backing off delay until we reconnect

// Start with a small delay and double it on each retry up to a maximum value
var delay = 5000;
var reconnectAttempts = 0;
var maxReconnectAttempts = 15;

while (true)
{
await Task.Delay(delay).ConfigureAwait(false);
reconnectAttempts++;

try
{
Console.WriteLine($"--> Attempting to reconnect to broker. This is attempt #{reconnectAttempts}.");
var connectResult = await client.ConnectAsync().ConfigureAwait(false);

if (connectResult.ReasonCode != HiveMQtt.MQTT5.ReasonCodes.ConnAckReasonCode.Success)
{
Console.WriteLine($"--> Failed to connect: {connectResult.ReasonString}");

// Double the delay with each failed retry to a maximum
delay = Math.Min(delay * 2, 60000);
Console.WriteLine($"--> Will delay for {delay / 1000} seconds until next try.");
}
else
{
Console.WriteLine("--> Reconnected successfully.");
break;
}
}
catch (HiveMQttClientException ex)
{
Console.WriteLine($"--> Failed to reconnect: {ex.Message}");

if (reconnectAttempts > maxReconnectAttempts)
{
Console.WriteLine("--> Maximum reconnect attempts exceeded. Exiting.");
break;
}

// Double the delay with each failed retry to a maximum
delay = Math.Min(delay * 2, 60000);
Console.WriteLine($"--> Will delay for {delay / 1000} seconds until next try.");
}
}
} // if (args.CleanDisconnect)

Console.WriteLine("--> Exiting AfterDisconnect handler.");
};

// Connect to the broker
var connectResult = await client.ConnectAsync().ConfigureAwait(false);
if (connectResult.ReasonCode != HiveMQtt.MQTT5.ReasonCodes.ConnAckReasonCode.Success)
Expand All @@ -25,7 +98,7 @@
}

// Example Settings
var wait = 50; // The delay between each message
var wait = 1000; // The delay between each message
Console.WriteLine($"Starting {wait / 1000} second loop... (press q to exit)");

// Topic to send messages to
Expand All @@ -39,32 +112,31 @@
//
while (true)
{
message_number++;
var payload = JsonSerializer.Serialize(new
if (client.IsConnected())
{
Content = "SendMessageOnLoop",
MessageNumber = message_number,
});

var message = new MQTT5PublishMessage
{
Topic = topic,
Payload = Encoding.ASCII.GetBytes(payload),
QoS = QualityOfService.ExactlyOnceDelivery,
};

var resultPublish = await client.PublishAsync(message).ConfigureAwait(false);
Console.WriteLine($"Published message {message_number} to topic {topic}: {resultPublish.QoS2ReasonCode}");
message_number++;
var payload = JsonSerializer.Serialize(new
{
Content = "SendMessageOnLoop",
MessageNumber = message_number,
});

await Task.Delay(wait).ConfigureAwait(false);
var message = new MQTT5PublishMessage
{
Topic = topic,
Payload = Encoding.ASCII.GetBytes(payload),
QoS = QualityOfService.ExactlyOnceDelivery,
};

if (Console.KeyAvailable)
var resultPublish = await client.PublishAsync(message).ConfigureAwait(false);
Console.WriteLine($"Published message {message_number} to topic {topic}: {resultPublish.QoS2ReasonCode}");
}
else
{
if (Console.ReadKey().Key == ConsoleKey.Q)
{
break;
}
Console.WriteLine("Client is not connected. Standing by...");
}

await Task.Delay(wait).ConfigureAwait(false);
}

Console.WriteLine("Disconnecting gracefully...");
Expand Down
9 changes: 2 additions & 7 deletions Examples/SendMessageOnLoop/SendMessageOnLoop.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,12 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<PropertyGroup>
<RestoreSources>$(RestoreSources);../../Source/HiveMQtt/bin/Debug/;https://api.nuget.org/v3/index.json</RestoreSources>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="HiveMQtt" Version="0.11.1" />
<ProjectReference Include="..\..\Source\HiveMQtt\HiveMQtt.csproj" />
</ItemGroup>

</Project>
Loading
Loading