Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

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