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

MqttConnectionHandler.cs 1.4 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using Microsoft.AspNetCore.Connections;
  2. using Microsoft.AspNetCore.Connections.Features;
  3. using MQTTnet.Adapter;
  4. using MQTTnet.Serializer;
  5. using MQTTnet.Server;
  6. using System;
  7. using System.Threading.Tasks;
  8. namespace MQTTnet.AspNetCore
  9. {
  10. public class MqttConnectionHandler : ConnectionHandler, IMqttServerAdapter
  11. {
  12. public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
  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. using (var adapter = new MqttConnectionContext(new MqttPacketSerializerAdapter(), connection))
  22. {
  23. var args = new MqttServerAdapterClientAcceptedEventArgs(adapter);
  24. ClientAccepted?.Invoke(this, args);
  25. await args.SessionTask;
  26. }
  27. }
  28. public Task StartAsync(IMqttServerOptions options)
  29. {
  30. return Task.CompletedTask;
  31. }
  32. public Task StopAsync()
  33. {
  34. return Task.CompletedTask;
  35. }
  36. public void Dispose()
  37. {
  38. }
  39. }
  40. }