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

MqttConnectionHandler.cs 1.5 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using Microsoft.AspNetCore.Connections;
  2. using Microsoft.AspNetCore.Connections.Features;
  3. using MQTTnet.Adapter;
  4. using MQTTnet.Server;
  5. using System;
  6. using System.Threading.Tasks;
  7. using MQTTnet.Formatter;
  8. namespace MQTTnet.AspNetCore
  9. {
  10. public class MqttConnectionHandler : ConnectionHandler, IMqttServerAdapter
  11. {
  12. public Func<IMqttChannelAdapter, Task> ClientHandler { get; set; }
  13. public override async Task OnConnectedAsync(ConnectionContext connection)
  14. {
  15. // required for websocket transport to work
  16. var transferFormatFeature = connection.Features.Get<ITransferFormatFeature>();
  17. if (transferFormatFeature != null)
  18. {
  19. transferFormatFeature.ActiveFormat = TransferFormat.Binary;
  20. }
  21. var writer = new SpanBasedMqttPacketWriter();
  22. var formatter = new MqttPacketFormatterAdapter(writer);
  23. using (var adapter = new MqttConnectionContext(formatter, connection))
  24. {
  25. var clientHandler = ClientHandler;
  26. if (clientHandler != null)
  27. {
  28. await clientHandler(adapter).ConfigureAwait(false);
  29. }
  30. }
  31. }
  32. public Task StartAsync(IMqttServerOptions options)
  33. {
  34. return Task.CompletedTask;
  35. }
  36. public Task StopAsync()
  37. {
  38. return Task.CompletedTask;
  39. }
  40. public void Dispose()
  41. {
  42. }
  43. }
  44. }