You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

95 lines
2.9 KiB

  1. using System;
  2. using System.IO;
  3. using System.Reflection;
  4. using System.Runtime.Versioning;
  5. using System.Threading.Tasks;
  6. using Microsoft.AspNetCore.Builder;
  7. using Microsoft.AspNetCore.Hosting;
  8. using Microsoft.Extensions.DependencyInjection;
  9. using Microsoft.Extensions.FileProviders;
  10. using Microsoft.Extensions.Logging;
  11. using MQTTnet.AspNetCore;
  12. using MQTTnet.Server;
  13. namespace MQTTnet.TestApp.AspNetCore2
  14. {
  15. public class Startup
  16. {
  17. // In class _Startup_ of the ASP.NET Core 2.0 project.
  18. public void ConfigureServices(IServiceCollection services)
  19. {
  20. services
  21. .AddHostedMqttServer(mqttServer => mqttServer.WithoutDefaultEndpoint())
  22. .AddMqttConnectionHandler()
  23. .AddConnections();
  24. }
  25. // In class _Startup_ of the ASP.NET Core 3.1 project.
  26. #if NETCOREAPP3_1
  27. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  28. {
  29. app.UseRouting();
  30. app.UseEndpoints(endpoints =>
  31. {
  32. endpoints.MapMqtt("/mqtt");
  33. });
  34. #else
  35. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  36. {
  37. app.UseConnections(c => c.MapMqtt("/mqtt"));
  38. #endif
  39. app.UseMqttServer(server =>
  40. {
  41. server.StartedHandler = new MqttServerStartedHandlerDelegate(async args =>
  42. {
  43. var frameworkName = GetType().Assembly.GetCustomAttribute<TargetFrameworkAttribute>()?
  44. .FrameworkName;
  45. var msg = new MqttApplicationMessageBuilder()
  46. .WithPayload($"Mqtt hosted on {frameworkName} is awesome")
  47. .WithTopic("message");
  48. while (true)
  49. {
  50. try
  51. {
  52. await server.PublishAsync(msg.Build());
  53. msg.WithPayload($"Mqtt hosted on {frameworkName} is still awesome at {DateTime.Now}");
  54. }
  55. catch (Exception e)
  56. {
  57. Console.WriteLine(e);
  58. }
  59. finally
  60. {
  61. await Task.Delay(TimeSpan.FromSeconds(2));
  62. }
  63. }
  64. });
  65. });
  66. app.Use((context, next) =>
  67. {
  68. if (context.Request.Path == "/")
  69. {
  70. context.Request.Path = "/Index.html";
  71. }
  72. return next();
  73. });
  74. app.UseStaticFiles();
  75. app.UseStaticFiles(new StaticFileOptions
  76. {
  77. RequestPath = "/node_modules",
  78. FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "node_modules"))
  79. });
  80. }
  81. }
  82. }