jhalbrecht

Xamarin Hermes mqtt client test

Nov 3rd, 2017
309
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.22 KB | None | 0 0
  1. // Xamarin Hermes mqtt client test
  2. using System;
  3. using System.Net;
  4. using System.Net.Mqtt;
  5. using System.Text;
  6. using System.Threading;
  7.  
  8. namespace MqttTest.Client
  9. {
  10.     class Program
  11.     {
  12.         const int loopDelayTime = 250;
  13.         const string topic = "test/chat/message";
  14.         const string exitMessage = "exit";
  15.  
  16.         static void Main (string[] args)
  17.         {
  18.             bool isFinishing = false;
  19.             //var config = new MqttConfiguration { Port = 55555 };
  20.             var config = new MqttConfiguration { Port = 1883 };
  21.             //var client = MqttClient.CreateAsync("10.67.1.69", config).Result;
  22.             var client = MqttClient.CreateAsync("192.168.1.222", config).Result;
  23.             var clientId = "XamarinClient";
  24.             var received = "";
  25.  
  26.             client.ConnectAsync (new MqttClientCredentials (clientId)).Wait ();
  27.             client.SubscribeAsync (topic, MqttQualityOfService.AtLeastOnce).Wait ();
  28.             client.MessageStream.Subscribe (message => {
  29.                 if (isFinishing)
  30.                     return;
  31.  
  32.                 //var data = Encoding.UTF8.GetString (message.Payload).Split (new string[] { ":" }, StringSplitOptions.None);
  33.                 var data = Encoding.UTF8.GetString(message.Payload);
  34.                 //Console.WriteLine ($"Message Received from {data[0]}:{data[1]}");
  35.                 Console.WriteLine($"Message Received; {data}");
  36.                 //PublishAsync (client, clientId, exitMessage);
  37.  
  38.                 //Send exit to server
  39.                 //received = data[1];
  40.  
  41.                 //if (received == exitMessage)
  42.                 //  isFinishing = true;
  43.             });
  44.  
  45.             Console.WriteLine ($"Client connected successfully to {client.Id}:{config.Port}");
  46.             Console.WriteLine ($"Awaiting messages...");
  47.  
  48.             PublishAsync (client, clientId, "Connected.");
  49.  
  50.             //while (received != exitMessage) {
  51.             //  Thread.Sleep (loopDelayTime);
  52.             //}
  53.             //Console.WriteLine ("Shutting down... Received exit command.");
  54.         }
  55.  
  56.         static void PublishAsync (IMqttClient client, string clientId, string message)
  57.         {
  58.             Console.WriteLine ($"Sending message: {message}");
  59.             client.PublishAsync (new MqttApplicationMessage (topic, Encoding.UTF8.GetBytes ($"{clientId}:{message}")), MqttQualityOfService.AtLeastOnce).Wait();
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment