Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Startup.cs 2.7 KiB

7 år sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. .AddConnections();
  25. }
  26. // In class _Startup_ of the ASP.NET Core 2.0 project.
  27. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  28. {
  29. app.UseConnections(c => c.MapConnectionHandler<MqttConnectionHandler>("/mqtt", options => {
  30. options.WebSockets.SubProtocolSelector = MQTTnet.AspNetCore.ApplicationBuilderExtensions.SelectSubProtocol;
  31. }));
  32. //app.UseMqttEndpoint();
  33. app.UseMqttServer(server =>
  34. {
  35. server.Started += async (sender, args) =>
  36. {
  37. var msg = new MqttApplicationMessageBuilder()
  38. .WithPayload("Mqtt is awesome")
  39. .WithTopic("message");
  40. while (true)
  41. {
  42. try
  43. {
  44. await server.PublishAsync(msg.Build());
  45. msg.WithPayload("Mqtt is still awesome at " + DateTime.Now);
  46. }
  47. catch (Exception e)
  48. {
  49. Console.WriteLine(e);
  50. }
  51. finally
  52. {
  53. await Task.Delay(TimeSpan.FromSeconds(2));
  54. }
  55. }
  56. };
  57. });
  58. app.Use((context, next) =>
  59. {
  60. if (context.Request.Path == "/")
  61. {
  62. context.Request.Path = "/Index.html";
  63. }
  64. return next();
  65. });
  66. app.UseStaticFiles();
  67. app.UseStaticFiles(new StaticFileOptions
  68. {
  69. RequestPath = "/node_modules",
  70. FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "node_modules"))
  71. });
  72. }
  73. }
  74. }