Files
MQTTnet/Tests/MQTTnet.TestApp.NetCore/ServerTest.cs
T
2017-11-23 22:50:26 +01:00

89 lines
3.3 KiB
C#

using System;
using System.Text;
using System.Threading.Tasks;
using MQTTnet.Core.Protocol;
using MQTTnet.Core.Server;
using MQTTnet.Diagnostics;
namespace MQTTnet.TestApp.NetCore
{
public static class ServerTest
{
public static async Task RunAsync()
{
try
{
MqttNetConsoleLogger.ForwardToConsole();
var options = new MqttServerOptions
{
ConnectionValidator = p =>
{
if (p.ClientId == "SpecialClient")
{
if (p.Username != "USER" || p.Password != "PASS")
{
return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
}
}
return MqttConnectReturnCode.ConnectionAccepted;
},
Storage = new RetainedMessageHandler(),
ApplicationMessageInterceptor = context =>
{
if (MqttTopicFilterComparer.IsMatch(context.ApplicationMessage.Topic, "/myTopic/WithTimestamp/#"))
{
// Replace the payload with the timestamp. But also extending a JSON
// based payload with the timestamp is a suitable use case.
context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(DateTime.Now.ToString("O"));
}
},
SubscriptionInterceptor = context =>
{
if (context.TopicFilter.Topic.StartsWith("admin/foo/bar") && context.ClientId != "theAdmin")
{
context.AcceptSubscription = false;
}
if (context.TopicFilter.Topic.StartsWith("the/secret/stuff") && context.ClientId != "Imperator")
{
context.AcceptSubscription = false;
context.CloseConnection = true;
}
}
};
// Extend the timestamp for all messages from clients.
// Protect several topics from being subscribed from every client.
//var certificate = new X509Certificate(@"C:\certs\test\test.cer", "");
//options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);
//options.ConnectionBacklog = 5;
//options.DefaultEndpointOptions.IsEnabled = true;
//options.TlsEndpointOptions.IsEnabled = false;
var mqttServer = new MqttFactory().CreateMqttServer();
mqttServer.ClientDisconnected += (s, e) =>
{
Console.Write("Client disconnected event fired.");
};
await mqttServer.StartAsync(options);
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
await mqttServer.StopAsync();
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
}