Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

68 rader
2.1 KiB

  1. using Microsoft.AspNetCore.Http;
  2. using MQTTnet.Adapter;
  3. using MQTTnet.Diagnostics;
  4. using MQTTnet.Formatter;
  5. using MQTTnet.Implementations;
  6. using MQTTnet.Server;
  7. using System;
  8. using System.Net.WebSockets;
  9. using System.Threading.Tasks;
  10. namespace MQTTnet.AspNetCore
  11. {
  12. public sealed class MqttWebSocketServerAdapter : IMqttServerAdapter
  13. {
  14. readonly IMqttNetLogger _rootLogger;
  15. public MqttWebSocketServerAdapter(IMqttNetLogger logger)
  16. {
  17. _rootLogger = logger ?? throw new ArgumentNullException(nameof(logger));
  18. }
  19. public Func<IMqttChannelAdapter, Task> ClientHandler { get; set; }
  20. public Task StartAsync(IMqttServerOptions options)
  21. {
  22. return Task.CompletedTask;
  23. }
  24. public Task StopAsync()
  25. {
  26. return Task.CompletedTask;
  27. }
  28. public async Task RunWebSocketConnectionAsync(WebSocket webSocket, HttpContext httpContext)
  29. {
  30. if (webSocket == null) throw new ArgumentNullException(nameof(webSocket));
  31. var endpoint = $"{httpContext.Connection.RemoteIpAddress}:{httpContext.Connection.RemotePort}";
  32. var clientCertificate = await httpContext.Connection.GetClientCertificateAsync().ConfigureAwait(false);
  33. try
  34. {
  35. var isSecureConnection = clientCertificate != null;
  36. var clientHandler = ClientHandler;
  37. if (clientHandler != null)
  38. {
  39. var writer = new SpanBasedMqttPacketWriter();
  40. var formatter = new MqttPacketFormatterAdapter(writer);
  41. var channel = new MqttWebSocketChannel(webSocket, endpoint, isSecureConnection, clientCertificate);
  42. using (var channelAdapter = new MqttChannelAdapter(channel, formatter, null, _rootLogger))
  43. {
  44. await clientHandler(channelAdapter).ConfigureAwait(false);
  45. }
  46. }
  47. }
  48. finally
  49. {
  50. clientCertificate?.Dispose();
  51. }
  52. }
  53. public void Dispose()
  54. {
  55. }
  56. }
  57. }