Não pode escolher mais do que 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.
 
 
 
 

74 linhas
1.7 KiB

  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using MQTTnet;
  5. using MQTTnet.AspNetCore;
  6. using MQTTnet.Server;
  7. var builder = WebApplication.CreateBuilder(args);
  8. builder.Services.AddRazorPages();
  9. // Setup MQTT stuff.
  10. builder.Services.AddMqttServer();
  11. builder.Services.AddConnections();
  12. var app = builder.Build();
  13. if (!app.Environment.IsDevelopment())
  14. {
  15. app.UseExceptionHandler("/Error");
  16. }
  17. app.UseStaticFiles();
  18. app.UseRouting();
  19. app.UseAuthorization();
  20. app.MapRazorPages();
  21. // Setup MQTT stuff.
  22. app.UseEndpoints(endpoints =>
  23. {
  24. endpoints.MapMqtt("/mqtt");
  25. });
  26. app.UseMqttServer(server =>
  27. {
  28. server.StartedAsync += args =>
  29. {
  30. _ = Task.Run(async () =>
  31. {
  32. var mqttApplicationMessage = new MqttApplicationMessageBuilder()
  33. .WithPayload($"Test application message from MQTTnet server.")
  34. .WithTopic("message")
  35. .Build();
  36. while (true)
  37. {
  38. try
  39. {
  40. await server.InjectApplicationMessage(new InjectedMqttApplicationMessage(mqttApplicationMessage)
  41. {
  42. SenderClientId = "server"
  43. });
  44. }
  45. catch (Exception e)
  46. {
  47. Console.WriteLine(e);
  48. }
  49. finally
  50. {
  51. await Task.Delay(TimeSpan.FromSeconds(5));
  52. }
  53. }
  54. });
  55. return Task.CompletedTask;
  56. };
  57. });
  58. app.Run();