Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

95 rader
2.8 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.Diagnostics;
  9. using MQTTnet.Core.Serializer;
  10. using MQTTnet.Core.Server;
  11. using MQTTnet.Implementations;
  12. namespace MQTTnet.TestApp.AspNetCore2
  13. {
  14. public class MqttWebSocketServerAdapter : IMqttServerAdapter, IDisposable
  15. {
  16. private readonly MqttNetTrace _trace;
  17. public MqttWebSocketServerAdapter(MqttNetTrace trace)
  18. {
  19. _trace = trace ?? throw new ArgumentNullException(nameof(trace));
  20. }
  21. public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
  22. public Task StartAsync(MqttServerOptions options)
  23. {
  24. return Task.CompletedTask;
  25. }
  26. public Task StopAsync()
  27. {
  28. return Task.FromResult(0);
  29. }
  30. public Task AcceptWebSocketAsync(WebSocket webSocket)
  31. {
  32. if (webSocket == null) throw new ArgumentNullException(nameof(webSocket));
  33. var channel = new MqttWebSocketServerChannel(webSocket);
  34. var clientAdapter = new MqttChannelCommunicationAdapter(channel, new MqttPacketSerializer(), _trace);
  35. var eventArgs = new MqttServerAdapterClientAcceptedEventArgs(clientAdapter);
  36. ClientAccepted?.Invoke(this, eventArgs);
  37. return eventArgs.SessionTask;
  38. }
  39. public void Dispose()
  40. {
  41. StopAsync();
  42. }
  43. private class MqttWebSocketServerChannel : IMqttCommunicationChannel, IDisposable
  44. {
  45. private readonly WebSocket _webSocket;
  46. public MqttWebSocketServerChannel(WebSocket webSocket)
  47. {
  48. _webSocket = webSocket ?? throw new ArgumentNullException(nameof(webSocket));
  49. RawReceiveStream = new WebSocketStream(_webSocket);
  50. }
  51. public Stream SendStream => RawReceiveStream;
  52. public Stream ReceiveStream => RawReceiveStream;
  53. public Stream RawReceiveStream { get; }
  54. public Task ConnectAsync()
  55. {
  56. return Task.CompletedTask;
  57. }
  58. public Task DisconnectAsync()
  59. {
  60. RawReceiveStream?.Dispose();
  61. if (_webSocket == null)
  62. {
  63. return Task.CompletedTask;
  64. }
  65. return _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
  66. }
  67. public void Dispose()
  68. {
  69. RawReceiveStream?.Dispose();
  70. SendStream?.Dispose();
  71. ReceiveStream?.Dispose();
  72. _webSocket?.Dispose();
  73. }
  74. }
  75. }
  76. }