選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 

62 行
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 Action<MqttServerAdapterClientAcceptedEventArgs> ClientAcceptedHandler { 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 channel = new MqttWebSocketChannel(webSocket, endpoint, isSecureConnection);
  37. var clientAdapter = new MqttChannelAdapter(channel, new MqttPacketFormatterAdapter(), _logger.CreateChildLogger(nameof(MqttWebSocketServerAdapter)));
  38. var eventArgs = new MqttServerAdapterClientAcceptedEventArgs(clientAdapter);
  39. ClientAcceptedHandler?.Invoke(eventArgs);
  40. if (eventArgs.SessionTask != null)
  41. {
  42. await eventArgs.SessionTask.ConfigureAwait(false);
  43. }
  44. }
  45. public void Dispose()
  46. {
  47. }
  48. }
  49. }