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.
 
 
 
 

80 lines
2.7 KiB

  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using MQTTnet.Client;
  5. using MQTTnet.Samples.Helpers;
  6. namespace MQTTnet.Samples.Client;
  7. public static class Client_Subscribe_Samples
  8. {
  9. public static async Task Handle_Received_Application_Message()
  10. {
  11. /*
  12. * This sample subscribes to a topic and processes the received message.
  13. */
  14. var mqttFactory = new MqttFactory();
  15. using (var mqttClient = mqttFactory.CreateMqttClient())
  16. {
  17. var mqttClientOptions = new MqttClientOptionsBuilder()
  18. .WithTcpServer("broker.hivemq.com")
  19. .Build();
  20. // Setup message handling before connecting so that queued messages
  21. // are also handled properly. When there is no event handler attached all
  22. // received messages get lost.
  23. mqttClient.ApplicationMessageReceivedAsync += e =>
  24. {
  25. Console.WriteLine("Received application message.");
  26. e.DumpToConsole();
  27. return Task.CompletedTask;
  28. };
  29. await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
  30. var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder()
  31. .WithTopicFilter(f => { f.WithTopic("mqttnet/samples/topic/2"); })
  32. .Build();
  33. await mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None);
  34. Console.WriteLine("MQTT client subscribed to topic.");
  35. Console.WriteLine("Press enter to exit.");
  36. Console.ReadLine();
  37. }
  38. }
  39. public static async Task Subscribe_Topic()
  40. {
  41. /*
  42. * This sample subscribes to a topic.
  43. */
  44. var mqttFactory = new MqttFactory();
  45. using (var mqttClient = mqttFactory.CreateMqttClient())
  46. {
  47. var mqttClientOptions = new MqttClientOptionsBuilder()
  48. .WithTcpServer("broker.hivemq.com")
  49. .Build();
  50. await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
  51. var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder()
  52. .WithTopicFilter(f => { f.WithTopic("mqttnet/samples/topic/1"); })
  53. .Build();
  54. var response = await mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None);
  55. Console.WriteLine("MQTT client subscribed to topic.");
  56. // The response contains additional data sent by the server after subscribing.
  57. response.DumpToConsole();
  58. }
  59. }
  60. }