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.1 KiB

hace 6 años
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using Microsoft.AspNetCore.Http;
  2. using MQTTnet.Adapter;
  3. using MQTTnet.Formatter;
  4. using MQTTnet.Implementations;
  5. using MQTTnet.Server;
  6. using System;
  7. using System.Net.WebSockets;
  8. using System.Threading.Tasks;
  9. using MQTTnet.Diagnostics.Logger;
  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. }