Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 

53 Zeilen
1.9 KiB

  1. using System;
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using System.Linq;
  5. using MQTTnet.Server;
  6. namespace MQTTnet.AspNetCore
  7. {
  8. public static class ApplicationBuilderExtensions
  9. {
  10. public static IApplicationBuilder UseMqttEndpoint(this IApplicationBuilder app, string path = "/mqtt")
  11. {
  12. app.UseWebSockets();
  13. app.Use(async (context, next) =>
  14. {
  15. if (!context.WebSockets.IsWebSocketRequest || context.Request.Path != path)
  16. {
  17. await next();
  18. return;
  19. }
  20. string subProtocol = null;
  21. if (context.Request.Headers.TryGetValue("Sec-WebSocket-Protocol", out var requestedSubProtocolValues))
  22. {
  23. // Order the protocols to also match "mqtt", "mqttv-3.1", "mqttv-3.11" etc.
  24. subProtocol = requestedSubProtocolValues
  25. .OrderByDescending(p => p.Length)
  26. .FirstOrDefault(p => p.ToLower().StartsWith("mqtt"));
  27. }
  28. var adapter = app.ApplicationServices.GetRequiredService<MqttWebSocketServerAdapter>();
  29. using (var webSocket = await context.WebSockets.AcceptWebSocketAsync(subProtocol))
  30. {
  31. var endpoint = $"{context.Connection.RemoteIpAddress}:{context.Connection.RemotePort}";
  32. await adapter.RunWebSocketConnectionAsync(webSocket, endpoint);
  33. }
  34. });
  35. return app;
  36. }
  37. public static IApplicationBuilder UseMqttServer(this IApplicationBuilder app, Action<IMqttServer> configure)
  38. {
  39. var server = app.ApplicationServices.GetRequiredService<IMqttServer>();
  40. configure(server);
  41. return app;
  42. }
  43. }
  44. }