25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MqttWebSocketServerAdapter.cs 2.1 KiB

6 년 전
6 년 전
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. }