mirror of
https://github.com/dotnet/MQTTnet.git
synced 2026-10-18 10:26:11 +08:00
initial version
This commit is contained in:
@@ -3,10 +3,11 @@
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<DebugType>Full</DebugType>
|
||||
<TargetFrameworks>netcoreapp2.0;net45</TargetFrameworks>
|
||||
<TargetFrameworks>netcoreapp2.0;net451</TargetFrameworks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.2" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -15,4 +16,10 @@
|
||||
<ProjectReference Include="..\..\MQTTnet.Core\MQTTnet.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Console">
|
||||
<Version>1.1.2</Version>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core;
|
||||
using MQTTnet.Core.Client;
|
||||
using MQTTnet.Core.Diagnostics;
|
||||
using MQTTnet.Core.ManagedClient;
|
||||
using MQTTnet.Core.Packets;
|
||||
using MQTTnet.Core.Protocol;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MQTTnet.TestApp.NetCore
|
||||
{
|
||||
@@ -13,14 +14,14 @@ namespace MQTTnet.TestApp.NetCore
|
||||
{
|
||||
public static async Task RunAsync()
|
||||
{
|
||||
MqttNetTrace.TraceMessagePublished += (s, e) =>
|
||||
{
|
||||
Console.WriteLine($">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}");
|
||||
if (e.TraceMessage.Exception != null)
|
||||
{
|
||||
Console.WriteLine(e.TraceMessage.Exception);
|
||||
}
|
||||
};
|
||||
var services = new ServiceCollection()
|
||||
.AddMqttClient()
|
||||
.AddLogging()
|
||||
.BuildServiceProvider();
|
||||
|
||||
services.GetService<ILoggerFactory>()
|
||||
.AddConsole();
|
||||
|
||||
|
||||
var options = new ManagedMqttClientOptions
|
||||
{
|
||||
@@ -35,7 +36,7 @@ namespace MQTTnet.TestApp.NetCore
|
||||
|
||||
try
|
||||
{
|
||||
var managedClient = new MqttClientFactory().CreateManagedMqttClient();
|
||||
var managedClient = services.GetRequiredService<ManagedMqttClient>();
|
||||
managedClient.ApplicationMessageReceived += (s, e) =>
|
||||
{
|
||||
Console.WriteLine(">> RECEIVED: " + e.ApplicationMessage.Topic);
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using MQTTnet.Core;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using MQTTnet.Core;
|
||||
using MQTTnet.Core.Client;
|
||||
using MQTTnet.Core.Packets;
|
||||
using MQTTnet.Core.Protocol;
|
||||
@@ -17,33 +19,58 @@ namespace MQTTnet.TestApp.NetCore
|
||||
{
|
||||
public static async Task RunAsync()
|
||||
{
|
||||
var server = Task.Factory.StartNew(RunServerAsync, TaskCreationOptions.LongRunning);
|
||||
var client = Task.Factory.StartNew(() => RunClientAsync(2000, TimeSpan.FromMilliseconds(10)), TaskCreationOptions.LongRunning);
|
||||
var services = new ServiceCollection()
|
||||
.AddMqttServer(options => {
|
||||
|
||||
options.ConnectionValidator = p =>
|
||||
{
|
||||
if (p.ClientId == "SpecialClient")
|
||||
{
|
||||
if (p.Username != "USER" || p.Password != "PASS")
|
||||
{
|
||||
return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
|
||||
}
|
||||
}
|
||||
|
||||
return MqttConnectReturnCode.ConnectionAccepted;
|
||||
};
|
||||
|
||||
options.DefaultCommunicationTimeout = TimeSpan.FromMinutes(10);
|
||||
})
|
||||
.AddMqttClient()
|
||||
.AddLogging()
|
||||
.BuildServiceProvider();
|
||||
|
||||
services.GetService<ILoggerFactory>()
|
||||
.AddConsole(minLevel: LogLevel.Warning, includeScopes: true);
|
||||
|
||||
Console.WriteLine("Press 'c' for concurrent sends. Otherwise in one batch.");
|
||||
var concurrent = Console.ReadKey(intercept: true).KeyChar == 'c';
|
||||
|
||||
var server = Task.Factory.StartNew(() => RunServerAsync(services), TaskCreationOptions.LongRunning);
|
||||
var client = Task.Factory.StartNew(() => RunClientAsync(2000, TimeSpan.FromMilliseconds(10), services, concurrent), TaskCreationOptions.LongRunning);
|
||||
|
||||
await Task.WhenAll(server, client).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static Task RunClientsAsync(int msgChunkSize, TimeSpan interval)
|
||||
private static Task RunClientsAsync(int msgChunkSize, TimeSpan interval, IServiceProvider serviceProvider, bool concurrent)
|
||||
{
|
||||
return Task.WhenAll(Enumerable.Range(0, 3).Select(i => Task.Run(() => RunClientAsync(msgChunkSize, interval))));
|
||||
return Task.WhenAll(Enumerable.Range(0, 3).Select(i => Task.Run(() => RunClientAsync(msgChunkSize, interval, serviceProvider, concurrent))));
|
||||
}
|
||||
|
||||
private static async Task RunClientAsync(int msgChunkSize, TimeSpan interval)
|
||||
private static async Task RunClientAsync(int msgChunkSize, TimeSpan interval, IServiceProvider serviceProvider, bool concurrent)
|
||||
{
|
||||
try
|
||||
{
|
||||
var options = new MqttClientTcpOptions
|
||||
{
|
||||
Server = "localhost",
|
||||
ClientId = "XYZ",
|
||||
ClientId = "Client1",
|
||||
CleanSession = true,
|
||||
DefaultCommunicationTimeout = TimeSpan.FromMinutes(10)
|
||||
};
|
||||
|
||||
var client = new MqttClientFactory().CreateMqttClient();
|
||||
client.ApplicationMessageReceived += (s, e) =>
|
||||
{
|
||||
};
|
||||
var client = serviceProvider.GetRequiredService<IMqttClient>();
|
||||
|
||||
client.Connected += async (s, e) =>
|
||||
{
|
||||
@@ -113,8 +140,7 @@ namespace MQTTnet.TestApp.NetCore
|
||||
.Select(i => CreateMessage())
|
||||
.ToList();
|
||||
|
||||
Console.WriteLine("Press 'c' for concurrent sends. Otherwise in one batch.");
|
||||
if (Console.ReadKey().KeyChar == 'c')
|
||||
if (concurrent)
|
||||
{
|
||||
//send concurrent (test for raceconditions)
|
||||
var sendTasks = msgs
|
||||
@@ -165,28 +191,11 @@ namespace MQTTnet.TestApp.NetCore
|
||||
return Task.Run(() => client.PublishAsync(applicationMessage));
|
||||
}
|
||||
|
||||
private static async Task RunServerAsync()
|
||||
private static async Task RunServerAsync(IServiceProvider serviceProvider)
|
||||
{
|
||||
try
|
||||
{
|
||||
var options = new MqttServerOptions
|
||||
{
|
||||
ConnectionValidator = p =>
|
||||
{
|
||||
if (p.ClientId == "SpecialClient")
|
||||
{
|
||||
if (p.Username != "USER" || p.Password != "PASS")
|
||||
{
|
||||
return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
|
||||
}
|
||||
}
|
||||
|
||||
return MqttConnectReturnCode.ConnectionAccepted;
|
||||
},
|
||||
DefaultCommunicationTimeout = TimeSpan.FromMinutes(10)
|
||||
};
|
||||
|
||||
var mqttServer = new MqttServerFactory().CreateMqttServer(options);
|
||||
var mqttServer = serviceProvider.GetRequiredService<IMqttServer>();
|
||||
var msgs = 0;
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
mqttServer.ApplicationMessageReceived += (sender, args) =>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using MQTTnet.Core;
|
||||
using MQTTnet.Core.Client;
|
||||
using MQTTnet.Core.Diagnostics;
|
||||
using MQTTnet.Core.Packets;
|
||||
using MQTTnet.Core.Protocol;
|
||||
using MQTTnet.Core.Server;
|
||||
@@ -12,6 +11,8 @@ using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MQTTnet.TestApp.NetCore
|
||||
{
|
||||
@@ -24,7 +25,7 @@ namespace MQTTnet.TestApp.NetCore
|
||||
Console.WriteLine("2 = Start server");
|
||||
Console.WriteLine("3 = Start performance test");
|
||||
Console.WriteLine("4 = Start managed client");
|
||||
|
||||
|
||||
var pressedKey = Console.ReadKey(true);
|
||||
if (pressedKey.KeyChar == '1')
|
||||
{
|
||||
@@ -48,17 +49,16 @@ namespace MQTTnet.TestApp.NetCore
|
||||
|
||||
private static async Task RunClientAsync()
|
||||
{
|
||||
MqttNetTrace.TraceMessagePublished += (s, e) =>
|
||||
{
|
||||
Console.WriteLine($">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}");
|
||||
if (e.TraceMessage.Exception != null)
|
||||
{
|
||||
Console.WriteLine(e.TraceMessage.Exception);
|
||||
}
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
var services = new ServiceCollection()
|
||||
.AddMqttServer()
|
||||
.AddLogging()
|
||||
.BuildServiceProvider();
|
||||
|
||||
services.GetService<ILoggerFactory>()
|
||||
.AddConsole();
|
||||
|
||||
var options = new MqttClientWebSocketOptions
|
||||
{
|
||||
Uri = "localhost",
|
||||
@@ -66,7 +66,7 @@ namespace MQTTnet.TestApp.NetCore
|
||||
CleanSession = true
|
||||
};
|
||||
|
||||
var client = new MqttClientFactory().CreateMqttClient();
|
||||
var client = services.GetRequiredService<IMqttClient>();
|
||||
client.ApplicationMessageReceived += (s, e) =>
|
||||
{
|
||||
Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
|
||||
@@ -139,7 +139,12 @@ namespace MQTTnet.TestApp.NetCore
|
||||
private static async void WikiCode()
|
||||
{
|
||||
{
|
||||
var client = new MqttClientFactory().CreateMqttClient(new CustomTraceHandler("Client 1"));
|
||||
var serviceProvider = new ServiceCollection()
|
||||
.AddMqttServer()
|
||||
.AddLogging()
|
||||
.BuildServiceProvider();
|
||||
|
||||
var client = serviceProvider.GetRequiredService<IMqttClient>();
|
||||
|
||||
var message = new MqttApplicationMessageBuilder()
|
||||
.WithTopic("MyTopic")
|
||||
@@ -159,28 +164,6 @@ namespace MQTTnet.TestApp.NetCore
|
||||
}
|
||||
}
|
||||
|
||||
public class CustomTraceHandler : IMqttNetTraceHandler
|
||||
{
|
||||
private readonly string _clientId;
|
||||
|
||||
public CustomTraceHandler(string clientId)
|
||||
{
|
||||
_clientId = clientId;
|
||||
}
|
||||
|
||||
public bool IsEnabled { get; } = true;
|
||||
|
||||
public void HandleTraceMessage(MqttNetTraceMessage traceMessage)
|
||||
{
|
||||
// Client ID is added to the trace message.
|
||||
Console.WriteLine($">> [{_clientId}] [{traceMessage.Timestamp:O}] [{traceMessage.ThreadId}] [{traceMessage.Source}] [{traceMessage.Level}]: {traceMessage.Message}");
|
||||
if (traceMessage.Exception != null)
|
||||
{
|
||||
Console.WriteLine(traceMessage.Exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class RetainedMessageHandler : IMqttServerStorage
|
||||
{
|
||||
private const string Filename = "C:\\MQTT\\RetainedMessages.json";
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Diagnostics;
|
||||
using MQTTnet.Core.Protocol;
|
||||
using MQTTnet.Core.Server;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MQTTnet.TestApp.NetCore
|
||||
{
|
||||
@@ -11,20 +12,15 @@ namespace MQTTnet.TestApp.NetCore
|
||||
{
|
||||
public static Task RunAsync()
|
||||
{
|
||||
MqttNetTrace.TraceMessagePublished += (s, e) =>
|
||||
{
|
||||
Console.WriteLine($">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}");
|
||||
if (e.TraceMessage.Exception != null)
|
||||
{
|
||||
Console.WriteLine(e.TraceMessage.Exception);
|
||||
}
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
var options = new MqttServerOptions
|
||||
var services = new ServiceCollection()
|
||||
.AddMqttServer()
|
||||
.AddLogging();
|
||||
|
||||
services.Configure<MqttServerOptions>(options =>
|
||||
{
|
||||
ConnectionValidator = p =>
|
||||
options.ConnectionValidator = p =>
|
||||
{
|
||||
if (p.ClientId == "SpecialClient")
|
||||
{
|
||||
@@ -35,22 +31,24 @@ namespace MQTTnet.TestApp.NetCore
|
||||
}
|
||||
|
||||
return MqttConnectReturnCode.ConnectionAccepted;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
options.Storage = new RetainedMessageHandler();
|
||||
options.Storage = new RetainedMessageHandler();
|
||||
|
||||
options.ApplicationMessageInterceptor = message =>
|
||||
{
|
||||
if (MqttTopicFilterComparer.IsMatch(message.Topic, "/myTopic/WithTimestamp/#"))
|
||||
options.ApplicationMessageInterceptor = message =>
|
||||
{
|
||||
// Replace the payload with the timestamp. But also extending a JSON
|
||||
// based payload with the timestamp is a suitable use case.
|
||||
message.Payload = Encoding.UTF8.GetBytes(DateTime.Now.ToString("O"));
|
||||
}
|
||||
if (MqttTopicFilterComparer.IsMatch(message.Topic, "/myTopic/WithTimestamp/#"))
|
||||
{
|
||||
// Replace the payload with the timestamp. But also extending a JSON
|
||||
// based payload with the timestamp is a suitable use case.
|
||||
message.Payload = Encoding.UTF8.GetBytes(DateTime.Now.ToString("O"));
|
||||
}
|
||||
|
||||
return message;
|
||||
};
|
||||
return message;
|
||||
};
|
||||
});
|
||||
|
||||
var serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
//var certificate = new X509Certificate(@"C:\certs\test\test.cer", "");
|
||||
//options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);
|
||||
@@ -58,7 +56,7 @@ namespace MQTTnet.TestApp.NetCore
|
||||
//options.DefaultEndpointOptions.IsEnabled = true;
|
||||
//options.TlsEndpointOptions.IsEnabled = false;
|
||||
|
||||
var mqttServer = new MqttServerFactory().CreateMqttServer(options);
|
||||
var mqttServer = serviceProvider.GetRequiredService<IMqttServer>();
|
||||
mqttServer.ClientDisconnected += (s, e) =>
|
||||
{
|
||||
Console.Write("Client disconnected event fired.");
|
||||
|
||||
Reference in New Issue
Block a user