25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

ApplicationBuilderExtensions.cs 1.9 KiB

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