No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

MqttWebSocketServerAdapter.cs 2.3 KiB

hace 6 años
hace 6 años
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. 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. }