You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

93 lines
2.9 KiB

  1. using System;
  2. using System.IO;
  3. using System.Net.WebSockets;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using MQTTnet.Core.Adapter;
  7. using MQTTnet.Core.Channel;
  8. using MQTTnet.Core.Server;
  9. using MQTTnet.Implementations;
  10. namespace MQTTnet.AspNetCore
  11. {
  12. public class MqttWebSocketServerAdapter : IMqttServerAdapter, IDisposable
  13. {
  14. private readonly IMqttCommunicationAdapterFactory _mqttCommunicationAdapterFactory;
  15. public MqttWebSocketServerAdapter(IMqttCommunicationAdapterFactory mqttCommunicationAdapterFactory)
  16. {
  17. _mqttCommunicationAdapterFactory = mqttCommunicationAdapterFactory ?? throw new ArgumentNullException(nameof(mqttCommunicationAdapterFactory));
  18. }
  19. public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
  20. public Task StartAsync(MqttServerOptions options)
  21. {
  22. return Task.CompletedTask;
  23. }
  24. public Task StopAsync()
  25. {
  26. return Task.CompletedTask;
  27. }
  28. public Task AcceptWebSocketAsync(WebSocket webSocket)
  29. {
  30. if (webSocket == null) throw new ArgumentNullException(nameof(webSocket));
  31. var channel = new MqttWebSocketServerChannel(webSocket);
  32. var clientAdapter = _mqttCommunicationAdapterFactory.CreateServerCommunicationAdapter(channel);
  33. var eventArgs = new MqttServerAdapterClientAcceptedEventArgs(clientAdapter);
  34. ClientAccepted?.Invoke(this, eventArgs);
  35. return eventArgs.SessionTask;
  36. }
  37. public void Dispose()
  38. {
  39. StopAsync();
  40. }
  41. private class MqttWebSocketServerChannel : IMqttCommunicationChannel, IDisposable
  42. {
  43. private readonly WebSocket _webSocket;
  44. public MqttWebSocketServerChannel(WebSocket webSocket)
  45. {
  46. _webSocket = webSocket ?? throw new ArgumentNullException(nameof(webSocket));
  47. RawReceiveStream = new WebSocketStream(_webSocket);
  48. }
  49. public Stream SendStream => RawReceiveStream;
  50. public Stream ReceiveStream => RawReceiveStream;
  51. public Stream RawReceiveStream { get; }
  52. public Task ConnectAsync()
  53. {
  54. return Task.CompletedTask;
  55. }
  56. public Task DisconnectAsync()
  57. {
  58. RawReceiveStream?.Dispose();
  59. if (_webSocket == null)
  60. {
  61. return Task.CompletedTask;
  62. }
  63. return _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
  64. }
  65. public void Dispose()
  66. {
  67. RawReceiveStream?.Dispose();
  68. SendStream?.Dispose();
  69. ReceiveStream?.Dispose();
  70. _webSocket?.Dispose();
  71. }
  72. }
  73. }
  74. }