您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

70 行
2.3 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 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. }