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.

Startup.cs 2.7 KiB

7 anos atrás
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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.AspNetCore;
  9. using MQTTnet.Server;
  10. namespace MQTTnet.TestApp.AspNetCore2
  11. {
  12. public class Startup
  13. {
  14. // In class _Startup_ of the ASP.NET Core 2.0 project.
  15. public void ConfigureServices(IServiceCollection services)
  16. {
  17. var mqttServerOptions = new MqttServerOptionsBuilder()
  18. .WithoutDefaultEndpoint()
  19. .Build();
  20. services
  21. .AddHostedMqttServer(mqttServerOptions)
  22. .AddMqttConnectionHandler()
  23. .AddConnections();
  24. }
  25. // In class _Startup_ of the ASP.NET Core 2.0 project.
  26. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  27. {
  28. app.UseConnections(c => c.MapConnectionHandler<MqttConnectionHandler>("/mqtt", options => {
  29. options.WebSockets.SubProtocolSelector = MQTTnet.AspNetCore.ApplicationBuilderExtensions.SelectSubProtocol;
  30. }));
  31. //app.UseMqttEndpoint();
  32. app.UseMqttServer(server =>
  33. {
  34. server.StartedHandler = new MqttServerStartedHandlerDelegate(async args =>
  35. {
  36. var msg = new MqttApplicationMessageBuilder()
  37. .WithPayload("Mqtt is awesome")
  38. .WithTopic("message");
  39. while (true)
  40. {
  41. try
  42. {
  43. await server.PublishAsync(msg.Build());
  44. msg.WithPayload("Mqtt is still awesome at " + DateTime.Now);
  45. }
  46. catch (Exception e)
  47. {
  48. Console.WriteLine(e);
  49. }
  50. finally
  51. {
  52. await Task.Delay(TimeSpan.FromSeconds(2));
  53. }
  54. }
  55. });
  56. });
  57. app.Use((context, next) =>
  58. {
  59. if (context.Request.Path == "/")
  60. {
  61. context.Request.Path = "/Index.html";
  62. }
  63. return next();
  64. });
  65. app.UseStaticFiles();
  66. app.UseStaticFiles(new StaticFileOptions
  67. {
  68. RequestPath = "/node_modules",
  69. FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "node_modules"))
  70. });
  71. }
  72. }
  73. }