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.

MqttWebSocketServerAdapter.cs 1.4 KiB

6 年之前
6 年之前
12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Net.WebSockets;
  3. using System.Threading.Tasks;
  4. using MQTTnet.Adapter;
  5. using MQTTnet.Diagnostics;
  6. using MQTTnet.Implementations;
  7. using MQTTnet.Serializer;
  8. using MQTTnet.Server;
  9. namespace MQTTnet.AspNetCore
  10. {
  11. public class MqttWebSocketServerAdapter : IMqttServerAdapter
  12. {
  13. public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
  14. public Task StartAsync(IMqttServerOptions options)
  15. {
  16. return Task.CompletedTask;
  17. }
  18. public Task StopAsync()
  19. {
  20. return Task.CompletedTask;
  21. }
  22. public async Task RunWebSocketConnectionAsync(WebSocket webSocket, string endpoint)
  23. {
  24. if (webSocket == null) throw new ArgumentNullException(nameof(webSocket));
  25. var clientAdapter = new MqttChannelAdapter(new MqttWebSocketChannel(webSocket, endpoint), new MqttPacketSerializer(), new MqttNetLogger().CreateChildLogger(nameof(MqttWebSocketServerAdapter)));
  26. var eventArgs = new MqttServerAdapterClientAcceptedEventArgs(clientAdapter);
  27. ClientAccepted?.Invoke(this, eventArgs);
  28. if (eventArgs.SessionTask != null)
  29. {
  30. await eventArgs.SessionTask.ConfigureAwait(false);
  31. }
  32. }
  33. public void Dispose()
  34. {
  35. StopAsync().GetAwaiter().GetResult();
  36. }
  37. }
  38. }