Skip to content

linfx/MqttFx

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MqttFx

c# mqtt 3.1.1 client


Install

PM> Install-Package MqttFx

Samples

    class Program
    {
        static async Task Main(string[] args)
        {
            var services = new ServiceCollection();
            services.AddMqttFxClient(options =>
            {
                options.Host = "broker.emqx.io";
                options.Port = 1883;
            });
            var container = services.BuildServiceProvider();

            var client = container.GetService<MqttClient>();

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

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

                var subscriptionRequests = new SubscriptionRequestsBuilder()
                    .WithTopicFilter(f => f.WithTopic("testtopic/a"))
                    .WithTopicFilter(f => f.WithTopic("testtopic/b").WithAtLeastOnceQoS())
                    .Build();

                var subscribeResult = await client.SubscribeAsync(subscriptionRequests);

                foreach (var item in subscribeResult.Items)
                {
                    Console.WriteLine($"+ ResultCode = {item.ResultCode}");
                }
            };

            client.ApplicationMessageReceivedAsync += async message =>
            {
                Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                Console.WriteLine($"+ Topic = {message.Topic}");
                Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(message.Payload)}");
                Console.WriteLine($"+ QoS = {message.Qos}");
                Console.WriteLine($"+ Retain = {message.Retain}");
                Console.WriteLine();

                await Task.CompletedTask;
            };

            var connectResult = await client.ConnectAsync();
            if (connectResult.Succeeded)
            {
                for (int i = 1; i <= 3; i++)
                {
                    await Task.Delay(500);
                    Console.WriteLine("### Publish Message ###");

                    var mesage = new ApplicationMessageBuilder()
                        .WithTopic("testtopic/ab")
                        .WithPayload($"HelloWorld: {i}")
                        .WithQos(MqttQos.AtLeastOnce)
                        .Build();

                    await client.PublishAsync(mesage);
                }
            }
            else
                Console.WriteLine("Connect Fail!");

            Console.ReadKey();
        }
    }

MQTT 规范

你可以通过以下链接了解与查阅 MQTT 协议:

MQTT 协议中文版

MQTT Version 3.1.1

MQTT Version 5.0

MQTT SN

About

MqttFx is a mqtt v3.1.1 client using DotNetty

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages