Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 

63 рядки
2.1 KiB

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