Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ApplicationBuilderExtensions.cs 1.7 KiB

pirms 7 gadiem
pirms 7 gadiem
pirms 7 gadiem
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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.Request.Path == path && context.WebSockets.IsWebSocketRequest)
  16. {
  17. string subprotocol = null;
  18. if (context.Request.Headers.TryGetValue("Sec-WebSocket-Protocol", out var requestedSubProtocolValues)
  19. && requestedSubProtocolValues.Count > 0
  20. && requestedSubProtocolValues.Any(v => v.ToLower() == "mqtt")
  21. )
  22. {
  23. subprotocol = "mqtt";
  24. }
  25. var adapter = app.ApplicationServices.GetRequiredService<MqttWebSocketServerAdapter>();
  26. using (var webSocket = await context.WebSockets.AcceptWebSocketAsync(subprotocol))
  27. {
  28. await adapter.AcceptWebSocketAsync(webSocket);
  29. }
  30. }
  31. else
  32. {
  33. await next();
  34. }
  35. });
  36. return app;
  37. }
  38. public static IApplicationBuilder UseMqttServer(this IApplicationBuilder app, Action<IMqttServer> configure)
  39. {
  40. var server = app.ApplicationServices.GetRequiredService<IMqttServer>();
  41. configure(server);
  42. return app;
  43. }
  44. }
  45. }