static void ConnectionServer()
        {
            var options = new MqttClientTcpOptions
            {
                // Port = 61613,
                Server       = "127.0.0.1",
                ClientId     = "c001",
                UserName     = "******",
                Password     = "******",
                CleanSession = true
            };


            var mqttClient = new MqttClientFactory().CreateMqttClient();

            mqttClient.ConnectAsync(options);

            mqttClient.SubscribeAsync(new List <TopicFilter> {
                new TopicFilter("家/客厅/空调/#", MqttQualityOfServiceLevel.AtMostOnce)
            });

            var appMsg = new MqttApplicationMessage("家/客厅/空调/开关", Encoding.UTF8.GetBytes("消息内容"), MqttQualityOfServiceLevel.AtMostOnce, false);

            mqttClient.PublishAsync(appMsg);
        }
Exemple #2
0
        private static async Task RunClientAsync(string[] arguments)
        {
            MqttTrace.TraceMessagePublished += (s, e) =>
            {
                Console.WriteLine($">> [{e.ThreadId}] [{e.Source}] [{e.Level}]: {e.Message}");
                if (e.Exception != null)
                {
                    Console.WriteLine(e.Exception);
                }
            };

            try
            {
                var options = new MqttClientOptions
                {
                    Server       = "localhost",
                    ClientId     = "XYZ",
                    CleanSession = true
                };

                var client = new MqttClientFactory().CreateMqttClient(options);
                client.ApplicationMessageReceived += (s, e) =>
                {
                    Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                    Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                    Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                    Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                    Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                    Console.WriteLine();
                };

                client.Connected += async(s, e) =>
                {
                    Console.WriteLine("### CONNECTED WITH SERVER ###");

                    await client.SubscribeAsync(new List <TopicFilter>
                    {
                        new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce)
                    });
                };

                client.Disconnected += async(s, e) =>
                {
                    Console.WriteLine("### DISCONNECTED FROM SERVER ###");
                    await Task.Delay(TimeSpan.FromSeconds(5));

                    try
                    {
                        await client.ConnectAsync();
                    }
                    catch
                    {
                        Console.WriteLine("### RECONNECTING FAILED ###");
                    }
                };

                try
                {
                    await client.ConnectAsync();
                }
                catch (Exception exception)
                {
                    Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
                }

                Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");

                var messageFactory = new MqttApplicationMessageFactory();
                while (true)
                {
                    Console.ReadLine();

                    var applicationMessage = messageFactory.CreateApplicationMessage("myTopic", "Hello World", MqttQualityOfServiceLevel.AtLeastOnce);
                    await client.PublishAsync(applicationMessage);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Exemple #3
0
        private static async Task RunClientAsync(int msgChunkSize, TimeSpan interval)
        {
            try
            {
                var options = new MqttClientOptions
                {
                    Server       = "localhost",
                    ClientId     = "XYZ",
                    CleanSession = true,
                    DefaultCommunicationTimeout = TimeSpan.FromMinutes(10)
                };

                var client = new MqttClientFactory().CreateMqttClient(options);
                client.ApplicationMessageReceived += (s, e) =>
                {
                };

                client.Connected += async(s, e) =>
                {
                    Console.WriteLine("### CONNECTED WITH SERVER ###");

                    await client.SubscribeAsync(new List <TopicFilter>
                    {
                        new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce)
                    });

                    Console.WriteLine("### SUBSCRIBED ###");
                };

                client.Disconnected += async(s, e) =>
                {
                    Console.WriteLine("### DISCONNECTED FROM SERVER ###");
                    await Task.Delay(TimeSpan.FromSeconds(5));

                    try
                    {
                        await client.ConnectAsync();
                    }
                    catch
                    {
                        Console.WriteLine("### RECONNECTING FAILED ###");
                    }
                };

                try
                {
                    await client.ConnectAsync();
                }
                catch (Exception exception)
                {
                    Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
                }

                Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");

                var testMessageCount = 10000;
                var message          = CreateMessage();
                var stopwatch        = Stopwatch.StartNew();
                for (var i = 0; i < testMessageCount; i++)
                {
                    await client.PublishAsync(message);
                }

                stopwatch.Stop();
                Console.WriteLine($"Sent 10.000 messages within {stopwatch.ElapsedMilliseconds} ms ({stopwatch.ElapsedMilliseconds / (float)testMessageCount} ms / message).");

                stopwatch.Restart();
                var sentMessagesCount = 0;
                while (stopwatch.ElapsedMilliseconds < 1000)
                {
                    await client.PublishAsync(message);

                    sentMessagesCount++;
                }

                Console.WriteLine($"Sending {sentMessagesCount} messages per second.");

                var last     = DateTime.Now;
                var msgCount = 0;

                while (true)
                {
                    var msgs = Enumerable.Range(0, msgChunkSize)
                               .Select(i => CreateMessage())
                               .ToList();

                    ////if (false)
                    ////{
                    ////    //send concurrent (test for raceconditions)
                    ////    var sendTasks = msgs
                    ////        .Select(msg => PublishSingleMessage(client, msg, ref msgCount))
                    ////        .ToList();

                    ////    await Task.WhenAll(sendTasks);
                    ////}
                    ////else
                    {
                        await client.PublishAsync(msgs);

                        msgCount += msgs.Count;
                        //send multiple
                    }



                    var now = DateTime.Now;
                    if (last < now - TimeSpan.FromSeconds(1))
                    {
                        Console.WriteLine($"sending {msgCount} inteded {msgChunkSize / interval.TotalSeconds}");
                        msgCount = 0;
                        last     = now;
                    }

                    await Task.Delay(interval).ConfigureAwait(false);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }