Advertisement
Guest User

Untitled

a guest
Jun 29th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. //Note that you can set more properties and also not set the port,
  2. //in which case the MQTT default will be used
  3. var configuration = new MqttConfiguration { Port = 55555 };
  4. //Creation of the MQTT client
  5. var client = await MqttClient.CreateAsync("192.168.1.29", configuration);
  6.  
  7. //MQTT connection of the client. You can pass optional args to the
  8. //ConnectAsync method and credentials
  9. await client.ConnectAsync(new MqttClientCredentials("testClient"));
  10.  
  11. //MQTT subscription to a topic. This only performs the protocol subscription,
  12. //which means that at this point it can start receiving messages from the Broker to that topic
  13. await client.SubscribeAsync("foo/bar/topic", MqttQualityOfService.AtLeastOnce);
  14.  
  15. //Rx Subscription to receive all the messages for the subscribed topics
  16. client.MessageStream.Subscribe(msg =>
  17. {
  18. //All the messages from the Broker to any subscribed topic will get here
  19. //The MessageStream is an Rx Observable, so you can filter the messages by topic with Linq to Rx
  20. //The message object has Topic and Payload properties. The Payload is a byte[] that you need to deserialize
  21. //depending on the type of the message
  22. Console.WriteLine($"Message received in topic {msg.Topic}");
  23. });
  24.  
  25. //Rx subscription sample to only receive the messages
  26. //to a specific topic (using System.Reactive.Linq)
  27. client
  28. .MessageStream
  29. .Where(msg => msg.Topic == "foo/bar/topic")
  30. .Subscribe(msg => Console.WriteLine($"Message received in topic foo/bar/topic"));
  31.  
  32. //MQTT publish to a topic
  33. //The message has a topic and the payload in byte[], which you are in charge of serializing from the original format
  34. //The PublishAsync method has some optional args
  35. var message = new MqttApplicationMessage("test/topic", Encoding.UTF8.GetBytes("Test String Message"));
  36.  
  37. await client.PublishAsync(message, MqttQualityOfService.AtLeastOnce);
  38.  
  39. //Method to unsubscribe a topic or many topics, which means that the message will no longer
  40. //be received in the MessageStream anymore
  41. await client.UnsubscribeAsync("foo/bar/topic");
  42.  
  43. //MQTT disconnection. Note that by now each client instance lifetime is from Connection to Disconnection
  44. //You can't re use an instance or re connect once you disconnected. You will need to create another MqttClient instance
  45. //This is currently reported as an issue and will be fixed for the next public version
  46. await client.DisconnectAsync();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement