jhalbrecht

Xamarin.Forms MainPage.xaml.cs hermes mqwtt client

Nov 3rd, 2017
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.35 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Net.Mqtt;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using Xamarin.Forms;
  9.  
  10. namespace XamFormsSample
  11. {
  12.     public partial class MainPage : ContentPage
  13.     {
  14.         const string topic = "test/chat/message";
  15.         //private HermesDataServices _mqttDataServices;
  16.         public MainPage()
  17.         {
  18.             Connect();
  19.             InitializeComponent();
  20.         }
  21.  
  22.         private static void Connect()
  23.         {
  24.             var config = new MqttConfiguration {Port = 1883};
  25.             var client = MqttClient.CreateAsync("192.168.1.222", config).Result;
  26.             Debug.WriteLine($"client is a: {client.GetType()} type."); // jha
  27.             var clientId = "XamarinClient";
  28.             client.ConnectAsync(new MqttClientCredentials(clientId)).Wait();
  29.             client.SubscribeAsync(topic, MqttQualityOfService.AtLeastOnce).Wait();
  30.             client.MessageStream.Subscribe(message =>
  31.             {
  32.                 var data = Encoding.UTF8.GetString(message.Payload);
  33.                 Console.WriteLine($"Message Received from {data}");
  34.             });
  35.             Console.WriteLine($"Client connected successfully to {client.Id}:{config.Port}");
  36.             Console.WriteLine($"Awaiting messages...");
  37.         }
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment