static void Main(string[] args) { try { Console.WriteLine("Initializing sender"); using (Publisher publisher = new Publisher()) { publisher.Connect(); Console.WriteLine("Press <ENTER> to start sending"); Console.ReadLine(); Contact contact = CreateContact(); Console.WriteLine("Sending contact"); publisher.Send("CACTopic.Message", contact); } } catch (Exception ex) { Console.WriteLine("Exception: " + ex.ToString()); } finally { Console.WriteLine("Press <ENTER> to shut down."); Console.ReadLine(); } }
public static void Start() { try { Console.WriteLine("Starting Publisher...."); var connectionOption = new ConnectionOptions("127.0.0.1", 1883); //var connectionOption = new ConnectionOptions("127.0.0.1", 1884); var credential = new Credentials("PublisherFromPublisherCode", "", ""); var publisher = new Publisher(new ConsoleLogger()); publisher.Create(connectionOption, credential); publisher.OnConnected += eventArgs => { Console.WriteLine("Connected successfully with MQTT Brokers."); }; publisher.OnDisconnected += eventArgs => { Console.WriteLine("Disconnected from MQTT Brokers."); }; publisher.OnMessageReceived += eventArgs => { try { string topic = eventArgs.ApplicationMessage.Topic; if (string.IsNullOrWhiteSpace(topic) == false) { string payload = Encoding.UTF8.GetString(eventArgs.ApplicationMessage.Payload); Console.WriteLine($"Topic: {topic}. Message Received: {payload}"); } } catch (Exception ex) { Console.WriteLine(ex.Message, ex); } }; publisher.Connect(); PublishMessage(publisher); //To keep the app running in container //https://stackoverflow.com/questions/38549006/docker-container-exits-immediately-even-with-console-readline-in-a-net-core-c Task.Run(() => Thread.Sleep(Timeout.Infinite)).Wait(); publisher.Disconnect(); } catch (Exception e) { Console.WriteLine(e); throw; } }