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

Support for hosting extensions #1653

Open
wants to merge 21 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion .github/workflows/ReleaseNotes.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
* [Client] Added support for custom CA chain validation (#1851, thanks to @rido-min).
* [Client] Added support for custom CA chain validation (#1851, thanks to @rido-min).
* [Client] Fixed handling of unobserved tasks exceptions (#1871).
* [Client] Fixed not specified ReasonCode when using _SendExtendedAuthenticationExchangeDataAsync_ (#1882, thanks to @rido-min).
* [Server] Fixed not working _UpdateRetainedMessageAsync_ public api (#1858, thanks to @kimdiego2098).
* [Server] Added support for custom DISCONNECT packets when stopping the server or disconnect a client (BREAKING CHANGE!, #1846).
* [Server] Added new property to stop the server from accepting new connections even if it is running (#1846).
* [Server] Added a new extension nuget which allows hosting a MQTT server via the Microsoft.Extensions.Hosting library (#1653, thanks to @YAJeff).
22 changes: 21 additions & 1 deletion MQTTnet.sln
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@


Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31919.166
Expand Down Expand Up @@ -32,6 +32,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MQTTnet.TestApp", "Source\M
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MQTTnet.AspTestApp", "Source\MQTTnet.AspTestApp\MQTTnet.AspTestApp.csproj", "{72867E4C-4E15-4E8E-8FAB-AE9253286BBC}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.Extensions.Hosting", "Source\MQTTnet.Extensions.Hosting\MQTTnet.Extensions.Hosting.csproj", "{B53FC20B-862C-4F8F-B9FF-E8C8D76A870D}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{26138A7E-435D-4C37-92B8-F506C640266D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MQTTnet.Extensions.Hosting.Tests", "Source\MQTTnet.Extensions.Hosting.Tests\MQTTnet.Extensions.Hosting.Tests.csproj", "{C4DE2742-2177-4AD0-BC01-74F29E9595C3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -82,11 +88,25 @@ Global
{72867E4C-4E15-4E8E-8FAB-AE9253286BBC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{72867E4C-4E15-4E8E-8FAB-AE9253286BBC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{72867E4C-4E15-4E8E-8FAB-AE9253286BBC}.Release|Any CPU.Build.0 = Release|Any CPU
{B53FC20B-862C-4F8F-B9FF-E8C8D76A870D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B53FC20B-862C-4F8F-B9FF-E8C8D76A870D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B53FC20B-862C-4F8F-B9FF-E8C8D76A870D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B53FC20B-862C-4F8F-B9FF-E8C8D76A870D}.Release|Any CPU.Build.0 = Release|Any CPU
{C4DE2742-2177-4AD0-BC01-74F29E9595C3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C4DE2742-2177-4AD0-BC01-74F29E9595C3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C4DE2742-2177-4AD0-BC01-74F29E9595C3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C4DE2742-2177-4AD0-BC01-74F29E9595C3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{72867E4C-4E15-4E8E-8FAB-AE9253286BBC} = {26138A7E-435D-4C37-92B8-F506C640266D}
{A238BBBF-C75F-482D-9CC3-BB34ABA9B675} = {26138A7E-435D-4C37-92B8-F506C640266D}
{B270F32A-9F3E-42EE-A989-813E35E29ADB} = {26138A7E-435D-4C37-92B8-F506C640266D}
{175D5340-CC5B-4542-939D-4E7D15A0BC8D} = {26138A7E-435D-4C37-92B8-F506C640266D}
{C4DE2742-2177-4AD0-BC01-74F29E9595C3} = {26138A7E-435D-4C37-92B8-F506C640266D}
{2F516E76-AAC4-4219-B7D1-34CDD3CFF381} = {26138A7E-435D-4C37-92B8-F506C640266D}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {07536672-5CBC-4BE3-ACE0-708A431A7894}
Expand Down
1 change: 1 addition & 0 deletions Samples/MQTTnet.Samples.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
<ProjectReference Include="..\Source\MQTTnet.Extensions.ManagedClient\MQTTnet.Extensions.ManagedClient.csproj" />
<ProjectReference Include="..\Source\MQTTnet.Extensions.Rpc\MQTTnet.Extensions.Rpc.csproj" />
<ProjectReference Include="..\Source\MQTTnet.Extensions.WebSocket4Net\MQTTnet.Extensions.WebSocket4Net.csproj" />
<ProjectReference Include="..\Source\MQTTnet.Extensions.Hosting\MQTTnet.Extensions.Hosting.csproj" />
<ProjectReference Include="..\Source\MQTTnet\MQTTnet.csproj" />
</ItemGroup>

Expand Down
44 changes: 44 additions & 0 deletions Samples/Server/Server_Hosting_Extensions_Samples.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Global
// ReSharper disable InconsistentNaming
// ReSharper disable EmptyConstructor
// ReSharper disable MemberCanBeMadeStatic.Local

using Microsoft.Extensions.Hosting;
using MQTTnet.Extensions.Hosting.Extensions;

namespace MQTTnet.Samples.Server;

public static class Server_Hosting_Extensions_Samples
{
public static Task Start_Server()
{
var builder = new HostBuilder();

builder.UseMqttServer(
mqtt =>
{
mqtt.WithDefaultEndpoint();
});

var host = builder.Build();
return host.RunAsync();
}

public static Task Start_Simple_Server()
{
var host = new HostBuilder().UseMqttServer().Build();

return host.RunAsync();
}

// This could be called as a top-level statement in a Program.cs file
public static Task Start_Single_Line_Server()
{
return new HostBuilder().UseMqttServer().Build().RunAsync();
}
}
198 changes: 198 additions & 0 deletions Source/MQTTnet.Extensions.Hosting.Tests/Hosting_Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
#if NET6_0_OR_GREATER
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MQTTnet.Extensions.Hosting.Extensions;
using MQTTnet.Server;

namespace MQTTnet.Tests.Server
{
[TestClass]
public sealed class Hosting_Tests
{
[TestMethod]
public async Task Advanced_Host_Configuration()
{
var syncLock = new object();
var connectedClientCount = 0;
var host = new HostBuilder().UseMqttServer(
mqtt =>
{
mqtt.WithDefaultEndpoint().WithKeepAlive();

mqtt.ClientConnectedAsync += e =>
{
lock (syncLock)
{
connectedClientCount++;
}

return Task.CompletedTask;
};
})
.Build();

await host.StartAsync();

// Perform client connect test
try
{
var factory = new MqttFactory();
var client = factory.CreateMqttClient();
var options = factory.CreateClientOptionsBuilder();
options.WithTcpServer("127.0.0.1");

await client.ConnectAsync(options.Build());
}
finally
{
await host.StopAsync();
}

Assert.AreEqual(1, connectedClientCount);
}

[TestMethod]
public async Task Custom_Host_Configuration()
{
var host = new HostBuilder().UseMqttServer(
mqtt =>
{
mqtt.WithDefaultEndpoint().WithKeepAlive();
})
.Build();
await host.StartAsync();

// Perform client connect test
try
{
var factory = new MqttFactory();
var client = factory.CreateMqttClient();
var options = factory.CreateClientOptionsBuilder();
options.WithTcpServer("127.0.0.1");

await client.ConnectAsync(options.Build());
}
finally
{
await host.StopAsync();
}
}

[TestMethod]
public async Task Default_Host_Configuration()
{
var host = new HostBuilder().UseMqttServer().Build();
await host.StartAsync();

// Perform client connect test
try
{
var factory = new MqttFactory();
var client = factory.CreateMqttClient();
var options = factory.CreateClientOptionsBuilder();
options.WithTcpServer("127.0.0.1");

await client.ConnectAsync(options.Build());
}
finally
{
await host.StopAsync();
}
}

[TestMethod]
public async Task Default_WebSocket_Configuration_Connect()
{
var host = new HostBuilder().UseMqttServer(
mqtt =>
{
mqtt.WithDefaultWebSocketEndpoint().WithDefaultWebSocketEndpointPort(8080);
})
.Build();
await host.StartAsync();

await Task.Delay(5000);

// Perform client connect test
try
{
var factory = new MqttFactory();
var client = factory.CreateMqttClient();
var options = factory.CreateClientOptionsBuilder();
options.WithWebSocketServer(o => o.WithUri("127.0.0.1:8080/mqtt"));

await client.ConnectAsync(options.Build());
}
finally
{
await host.StopAsync();
}
}

[TestMethod]
public async Task External_HttpListener_WebSocket_Configuration_Connect()
{
using (var tcs = new CancellationTokenSource())
{
var host = new HostBuilder().UseMqttServer().Build();
await host.StartAsync();

var httpListener = new HttpListener();
httpListener.Prefixes.Add("http://127.0.0.1:8080/");
httpListener.Start();

_ = Task.Factory.StartNew(
async () =>
{
while (!tcs.IsCancellationRequested)
{
try
{
var context = await httpListener.GetContextAsync();

if (context.Request.Url.AbsolutePath.Equals("/mqtt", StringComparison.OrdinalIgnoreCase) && context.Request.IsWebSocketRequest)
{
var mqttServer = host.Services.GetService<MqttServer>();
var webSocketContext = await context.AcceptWebSocketAsync("MQTT");
mqttServer.HandleWebSocketConnection(webSocketContext, context);
}
else
{
context.Response.StatusCode = 404;
context.Response.Close();
}
}
catch
{
}
}
});

await Task.Delay(5000);

// Perform client connect test
try
{
var factory = new MqttFactory();
var client = factory.CreateMqttClient();
var options = factory.CreateClientOptionsBuilder();
options.WithWebSocketServer(o => o.WithUri("127.0.0.1:8080/mqtt"));

await client.ConnectAsync(options.Build());
}
finally
{
await host.StopAsync();
httpListener.Stop();
}
}
}
}
}

#endif
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net6.0</TargetFrameworks>
<IsPackable>false</IsPackable>
<LangVersion>7.3</LangVersion>
<EnableNETAnalyzers>false</EnableNETAnalyzers>
<EnforceCodeStyleInBuild>false</EnforceCodeStyleInBuild>
<DisableImplicitAspNetCoreAnalyzers>true</DisableImplicitAspNetCoreAnalyzers>
<NoWarn>1591;NETSDK1138</NoWarn>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="MSTest.TestAdapter" Version="2.2.10" />
<PackageReference Include="MSTest.TestFramework" Version="2.2.10" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.2.0" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net6.0'">
<PackageReference Include="Microsoft.Extensions.Hosting">
<Version>6.0.0</Version>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\MQTTnet.Extensions.Hosting\MQTTnet.Extensions.Hosting.csproj" />
<ProjectReference Include="..\MQTTnet\MQTTnet.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
using System.Threading.Tasks;

namespace MQTTnet.Extensions.Hosting.Events
{
public delegate Task<bool> HttpWebSocketClientAuthenticationCallback();
}
Loading