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.
 
 
 
 

70 rindas
2.2 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 class MqttWebSocketServerAdapter : IMqttServerAdapter
  13. {
  14. private readonly IMqttNetLogger _logger;
  15. public MqttWebSocketServerAdapter(IMqttNetLogger 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. try
  35. {
  36. var isSecureConnection = clientCertificate != null;
  37. var clientHandler = ClientHandler;
  38. if (clientHandler != null)
  39. {
  40. var writer = new SpanBasedMqttPacketWriter();
  41. var formatter = new MqttPacketFormatterAdapter(writer);
  42. var channel = new MqttWebSocketChannel(webSocket, endpoint, isSecureConnection, clientCertificate);
  43. using (var channelAdapter = new MqttChannelAdapter(channel, formatter, _logger.CreateChildLogger(nameof(MqttWebSocketServerAdapter))))
  44. {
  45. await clientHandler(channelAdapter).ConfigureAwait(false);
  46. }
  47. }
  48. }
  49. finally
  50. {
  51. clientCertificate?.Dispose();
  52. }
  53. }
  54. public void Dispose()
  55. {
  56. }
  57. }
  58. }