.Net Core/.net 6/.Net 8 实现Mqtt客户端

.Net Core/.net 6/.Net 8 实现Mqtt客户端

直接上代码
nuget引用
MQTTnet

客户端代码


using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Packets;
using System.Text;

namespace Code.Mqtt
{
    /// <summary>
    /// Mqtt客户端
    /// </summary>
    public class MqttClientBase
    {
        /// <summary>
        /// 客户端
        /// </summary>
        public IMqttClient client;


        /// <summary>
        /// 订阅主题列表
        /// </summary>
        public List<string> Topics=new List<string>();



        public MqttClientOptions options;


        public MqttClientBaseOptions _opt;


        /// <summary>
        /// 主动断开连接
        /// </summary>
        public bool off = false;
        public bool isconn = false;


        /// <summary>
        /// 创建mqtt客户端,并值接传入初始参数
        /// </summary>
        /// <param name="opt"></param>
        public MqttClientBase(MqttClientBaseOptions opt)
        {
            this._opt = opt;


            //创建客户端
            client = new MqttFactory().CreateMqttClient();

            options =new MqttClientOptions() { 
                ClientId=_opt.clientId,
                ChannelOptions=new MqttClientTcpOptions()
                {
                    Server=_opt.server,
                    Port=_opt.port,
                },

                Credentials=new MqttClientCredentials(_opt.username,Encoding.UTF8.GetBytes(_opt.password)),

                //清理会话
                CleanSession=false,

                //设置心跳
                KeepAlivePeriod = TimeSpan.FromSeconds(30)
            };
        }

        /// <summary>
        /// 创建mqtt客户端,不传参数,
        /// 必须在调用 Connect之前调用过SetOption方法
        /// </summary>
        public MqttClientBase()
        {
            //创建客户端
            client = new MqttFactory().CreateMqttClient();
        }

        /// <summary>
        /// 设置参数
        /// </summary>
        /// <param name="opt"></param>
        public void SetOption(MqttClientBaseOptions opt)
        {
            options = new MqttClientOptions()
            {
                ClientId = _opt.clientId,
                ChannelOptions = new MqttClientTcpOptions()
                {
                    Server = _opt.server,
                    Port = _opt.port,
                },

                Credentials = new MqttClientCredentials(_opt.username, Encoding.UTF8.GetBytes(_opt.password)),

                //清理会话
                CleanSession = false,

                //设置心跳
                KeepAlivePeriod = TimeSpan.FromSeconds(30)
            };
        }


        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <param name="action">连接成功后执行</param>
        /// <param name="ConnectedAsync">连接成功事件</param>
        public void Connect(Action<MqttClientConnectedEventArgs> ConnectedAsync=null)
        {
            client.ConnectAsync(options);

            if(ConnectedAsync != null)
            {

                //连接成功事件
                client.ConnectedAsync += (args) =>
                {
                    ConnectedAsync(args);
                    return Task.CompletedTask;
                };

            }

        }

        /// <summary>
        /// 重连服务器
        /// 在连接断开事件中调用,即可实现无限轮询
        /// </summary>
        /// <param name="t">是否重复尝试重连</param>
        /// <param name="i">尝试次数</param>
        public void ReConnect()
        {
            try
            {
                client.ConnectAsync(options).Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }


        public async Task AddTopic(string topic)
        {


            //更新订阅
            client.SubscribeAsync(new MqttClientSubscribeOptions()
            {
                TopicFilters = new List<MqttTopicFilter>() {
                    new MqttTopicFilter { Topic = topic }
                }
            });

            
            //将主题名称加入列表
            Topics.Add(topic);
        }

        /// <summary>
        /// 取消订阅
        /// </summary>
        /// <param name="topic"></param>
        /// <returns></returns>
        public async Task DeleteTopic(string topic)
        {
            client.UnsubscribeAsync(new MqttClientUnsubscribeOptions()
            {
                TopicFilters = new List<string> { topic }
            });
            Topics.Remove(topic);
        }

        /// <summary>
        /// 发布消息
        /// </summary>
        /// <param name="topic">主题</param>
        /// <param name="content">内容</param>
        /// <returns></returns>
        public async Task Publish(string topic, string content)
        {
            if(client.IsConnected)
            {
                client.PublishAsync(new MqttApplicationMessage()
                {
                    Topic = topic,
                    Payload = Encoding.UTF8.GetBytes(content)
                });
            }
        }



        /// <summary>
        /// 主动断开连接
        /// </summary>
        public void Disconnect()
        {
            off = true;
            client.DisconnectAsync();
        }

        /// <summary>
        /// 断开连接事件
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public async Task DisconnectedAsync(Action<MqttClientDisconnectedEventArgs> action)
        {
            client.DisconnectedAsync += (args) => {
                action(args);
                return Task.CompletedTask;
            };
        }



        /// <summary>
        /// 接收消息事件
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public async Task Message(Action<string,string> action) {

            client.ApplicationMessageReceivedAsync += (args) =>
            {
                var topic = args.ApplicationMessage.Topic;
                var msg = args.ApplicationMessage.Payload.BToString();

                action(topic, msg);

                return Task.CompletedTask;
            };
        }



    }
}


调用

我这里是控制台项目



//初始化
var mqtt = new MqttClientBase(new MqttClientBaseOptions() { 
    clientId="client-1",
    username="username",
    password="password",
    server="127.0.0.1",
    port=10883
});

//断开连接事件
mqtt.DisconnectedAsync((e) => {
    Console.WriteLine("连接断开");

    //重连服务器
    mqtt.ReConnect();
});

//连接服务器
mqtt.Connect((args) => {
    /* 连接成功事件 */

    Console.WriteLine("连接成功");


    // 添加主题订阅,建议写到 连接成功事件 里面,这样重连后可以重新订阅主题
    mqtt.AddTopic("topic-1").Wait();
    mqtt.AddTopic("topic-2").Wait();
    mqtt.AddTopic("topic-3").Wait();

    // 取消主题订阅
    mqtt.DeleteTopic("topic-3").Wait();

    // 向指定主题推送消息
    mqtt.Publish("topic-1", "666666666").Wait();

});


// 收到来自服务器的消息 topic:主题  msg:消息内容
mqtt.Message((topic,msg) => { 

    Console.WriteLine($"收到消息:{topic}:{msg}");
});

// 这里暂停三秒,看三秒后主动断开连接效果
// Task.Delay(3000).Wait();

// 主动断开连接
//mqtt.Disconnect();


while (true)
{
    // 向指定主题推送消息
    mqtt.Publish("topic-1", Console.ReadLine());
}


m2mqtt.net 是一个开源的 MQTT 客户端库,可以用于在 .NET 平台上创建 MQTT 客户端。要创建多个客户端,可以使用 m2mqtt.net 提供的 MqttClient 实例来实现。 首先,我们需要在代码中引入 MqttClient 的命名空间: ``` using uPLibrary.Networking.M2Mqtt; using uPLibrary.Networking.M2Mqtt.Messages; ``` 接着,我们可以创建多个 MqttClient 实例,每个实例都代表一个 MQTT 客户端。例如,下面的代码创建了两个客户端: ``` // 创建客户端1 MqttClient client1 = new MqttClient("broker.hivemq.com"); // 创建客户端2 MqttClient client2 = new MqttClient("iot.eclipse.org"); ``` 接下来,我们可以给每个客户端设置回调函数,用于接收订阅主题的消息: ``` // 为客户端1设置回调函数 client1.MqttMsgPublishReceived += Client1_MqttMsgPublishReceived; // 为客户端2设置回调函数 client2.MqttMsgPublishReceived += Client2_MqttMsgPublishReceived; ``` 最后,我们可以连接每个客户端并订阅感兴趣的主题: ``` // 连接客户端1并订阅主题 client1.Connect("client1"); client1.Subscribe(new string[] { "topic1" }, new byte[] { 0 }); // 连接客户端2并订阅主题 client2.Connect("client2"); client2.Subscribe(new string[] { "topic2" }, new byte[] { 0 }); ``` 以上代码演示了如何创建多个 MQTT 客户端并订阅不同的主题。在实际应用中,我们可以根据需要创建更多的客户端,并为每个客户端设置不同的回调函数和订阅主题,以满足不同场景的需求。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_42199478

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值