Mqttnet4.x使用

官方示例:

https://github.com/dotnet/MQTTnet/tree/master/Samples

客户端:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Implementations;
using MQTTnet.Server;
using OneLink.Code.Config;
using OneLink.Code.Model.Throw;
using OneLink.Com.Public.Enum;

namespace OneLink.Com.Service.MqttService
{

    /// <summary>
    /// Mqtt客户端后台任务(自动统一注入)
    /// </summary>
    public class MqttClientService : IHostedService
    {
        public static IMqttClient _mqttClient;
        public MqttClientService(

            )
        {


        }


        /// <summary>
        /// 程序启动时调用
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            MqttClientTask();

        }

        /// <summary>
        /// 托管关闭时调用
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task StopAsync(CancellationToken cancellationToken)
        {

        }

        /// <summary>
        /// mqtt任务
        /// </summary>
        public void MqttClientTask()
        {
            if (GlobalConfig.GlobalMqttServiceConfig == null)
            {
                throw ApiExceptionBase.Fail(((int)ErrorCodeType.请配置Mqtt).ToString(), ErrorCodeType.请配置Mqtt.ToString());
            }


            _ = Task.Run(async () =>
            {

                Thread.Sleep(1000);
                try
                {

                    var mqttFactory = new MqttFactory();

                    //使用Build构建
                    var mqttClientOptions = new MqttClientOptionsBuilder()
                        .WithTcpServer(GlobalConfig.GlobalMqttServiceConfig.Ip, GlobalConfig.GlobalMqttServiceConfig.Port)
                        .WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V311)
                        .WithClientId("localhost_" + Guid.NewGuid())
                        .WithCleanSession(false)
                        .WithKeepAlivePeriod(TimeSpan.FromSeconds(30))
                        .WithCredentials(GlobalConfig.GlobalMqttServiceConfig.User, GlobalConfig.GlobalMqttServiceConfig.Pwd)
                    .Build();

                    _mqttClient = mqttFactory.CreateMqttClient();
                    //与3.1对比,事件订阅名称和接口已经变化
                    _mqttClient.DisconnectedAsync += MqttClient_DisconnectedAsync;
                    _mqttClient.ConnectedAsync += MqttClient_ConnectedAsync;
                    _mqttClient.ApplicationMessageReceivedAsync += MqttClient_ApplicationMessageReceivedAsync;
                    await _mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);

                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Mqtt客户端尝试连接出错:{ex.Message}");
                }
               
            });

        }



        private Task MqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
        {

            //主题
            var topic = arg.ApplicationMessage.Topic;
            //消息
            var msg = System.Text.Encoding.Default.GetString(arg.ApplicationMessage.Payload);
            Console.WriteLine("接收消息:" + topic);

            //推送消息
            _mqttClient.PublishStringAsync("/2345", "1231311");

            return Task.CompletedTask;
        }

        private async Task MqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
        {
            Console.WriteLine($"Mqtt客户端连接成功.");

            var mqttFactory = new MqttFactory();


            var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder()
                .WithTopicFilter(f => { f.WithTopic("/mqttnet/samples/topic/1"); })
                .Build();

            var response = await _mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None);

            Console.WriteLine("订阅消息");



        }

        private Task MqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
        {
            Console.WriteLine($"Mqtt客户端连接断开");
            //重连
            MqttClientTask();
            return Task.CompletedTask;
        }


    }

}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

智慧方

开发程序不易

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

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

打赏作者

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

抵扣说明:

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

余额充值