示例#1
4
文件: Program.cs 项目: 4058665/MQTT
        private static void DoThreadAction(object nameObj)
        {
            string name = nameObj.ToString();

            using (var c = new MqttClient(name))
            {
                c.OnUnsolicitedMessage += (c_OnUnsolicitedMessage);

                IPAddress address =
                    Dns.GetHostAddresses(Server)
                       .First(a => a.AddressFamily == AddressFamily.InterNetwork);

                var test = new IPEndPoint(address, Port);

                Console.WriteLine("{0} connecting...", name);
                DemandWorked(c.Connect(test));
                Console.WriteLine("{0} connected...", name);

                Console.WriteLine("{0} subscribing...", name);
                DemandWorked(c.Subscribe(
                    new[]
                        {
                            new Subscription(topic, QualityOfService.AtMostOnce),
                        }, null));
                Console.WriteLine("{0} subscribed...", name);

                waitForSubscribed.Set();
                done.WaitOne(-1);
                c.Disconnect(TimeSpan.FromSeconds(5));
            }
        }
示例#2
-1
文件: Program.cs 项目: 4058665/MQTT
        private static void DoWriteAction()
        {
            using (var c = new MqttClient(string.Format("{0}_{1}", topic, Thread.CurrentThread.ManagedThreadId)))
            {
                c.OnUnsolicitedMessage += c_OnUnsolicitedMessage;

                IPAddress address =
                    Dns.GetHostAddresses(Server)
                       .First(a => a.AddressFamily == AddressFamily.InterNetwork);

                var test = new IPEndPoint(address, Port);

                Console.WriteLine("WRITER connecting...");
                DemandWorked(c.Connect(test));
                Console.WriteLine("WRITER connected...");

                Console.WriteLine("Waiting for subscribe to finish...");
                waitForSubscribed.WaitOne();
                Console.WriteLine("Subscribe is ready!");

                int count = 0;
                while (done.WaitOne(0) == false)
                {
                    count++;
                    string msg = string.Format("This is message {0}!", count);
                    Console.WriteLine("WRITER: {0}", msg);
                    c.Publish(topic, msg, QualityOfService.AtMostOnce, null); // .Await();

                    Thread.Sleep(2000);
                }

                c.Disconnect(TimeSpan.FromSeconds(5));
            }
        }