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.
 
 
 
 

80 regels
2.4 KiB

  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using Microsoft.AspNetCore.Builder;
  5. using Microsoft.AspNetCore.Hosting;
  6. using Microsoft.Extensions.DependencyInjection;
  7. using Microsoft.Extensions.FileProviders;
  8. using MQTTnet;
  9. using MQTTnet.AspNetCore;
  10. using MQTTnet.Server;
  11. namespace MQTTnet.TestApp.AspNetCore2
  12. {
  13. public class Startup
  14. {
  15. // In class _Startup_ of the ASP.NET Core 2.0 project.
  16. public void ConfigureServices(IServiceCollection services)
  17. {
  18. var mqttServerOptions = new MqttServerOptionsBuilder()
  19. .WithoutDefaultEndpoint()
  20. .Build();
  21. services
  22. .AddHostedMqttServer(mqttServerOptions)
  23. .AddMqttConnectionHandler();
  24. }
  25. // In class _Startup_ of the ASP.NET Core 2.0 project.
  26. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  27. {
  28. app.UseMqttEndpoint();
  29. app.UseMqttServer(server =>
  30. {
  31. server.Started += async (sender, args) =>
  32. {
  33. var msg = new MqttApplicationMessageBuilder()
  34. .WithPayload("Mqtt is awesome")
  35. .WithTopic("message");
  36. while (true)
  37. {
  38. try
  39. {
  40. await server.PublishAsync(msg.Build());
  41. msg.WithPayload("Mqtt is still awesome at " + DateTime.Now);
  42. }
  43. catch (Exception e)
  44. {
  45. Console.WriteLine(e);
  46. }
  47. finally
  48. {
  49. await Task.Delay(TimeSpan.FromSeconds(2));
  50. }
  51. }
  52. };
  53. });
  54. app.Use((context, next) =>
  55. {
  56. if (context.Request.Path == "/")
  57. {
  58. context.Request.Path = "/Index.html";
  59. }
  60. return next();
  61. });
  62. app.UseStaticFiles();
  63. app.UseStaticFiles(new StaticFileOptions
  64. {
  65. RequestPath = "/node_modules",
  66. FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "node_modules"))
  67. });
  68. }
  69. }
  70. }