五分钟教会你在C#中通过MQTTnet包使用MQTT协议

一、下载MQTTNET包

二、编写代码

 public class Program
 {
     /// <summary>
     /// 发送消息
     /// </summary>
     /// <param name="args"></param>
     /// <returns></returns>
     static async Task Main(string[] args)
     {
         await Handle_Publish_Application_Message();   //发送
         await Handle_Received_Application_Message();  //接收
     }
     public static async Task Handle_Publish_Application_Message()
     {
         var mqttFactory = new MqttFactory();
         using(var mqttClient = mqttFactory.CreateMqttClient())
         {
             var mqttClientOptions = new MqttClientOptionsBuilder()
                 .WithTcpServer("broker服务器ip")
                 .Build();
             await mqttClient.ConnectAsync(mqttClientOptions,CancellationToken.None);
             var applicationMessage = new MqttApplicationMessageBuilder()
                 .WithTopic("mqttnet/samples/topic/1")
                 .WithPayload("欢迎来到MQTT的世界")
                 .Build();
             await mqttClient.PublishAsync(applicationMessage,CancellationToken.None);
             await mqttClient.DisconnectAsync();
         }
     }
     /// <summary>
     /// 接收消息
     /// </summary>
     /// <returns></returns>
     public static async Task Handle_Received_Application_Message()
     {
         var mqttFactory = new MqttFactory();
         using (var mqttClient = mqttFactory.CreateMqttClient())
         {

             var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("broker服务器ip").Build();
 
             await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
             var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder()
                 .WithTopicFilter(f => { f.WithTopic("mqttnet/samples/topic/1"); })
                 .WithTopicFilter(f => { f.WithTopic("mqttnet/samples/topic/2"); })
                 .WithTopicFilter(f => { f.WithTopic("mqttnet/samples/topic/3").WithRetainHandling(MqttRetainHandling.SendAtSubscribe); })
                 .Build();
             await mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None);
             mqttClient.ApplicationMessageReceivedAsync += e =>
             {
                 Console.WriteLine(e.ApplicationMessage.ConvertPayloadToString());
                 //缓存到redis
                 RedisHelper.AddStringValue_Redis(0, "message", e.ApplicationMessage.ConvertPayloadToString(), null);
                 return Task.CompletedTask;
             };
             Console.ReadLine();
         }
     }
 }

RedisHelper.cs:


    /// <summary>
    /// Redis基础操作帮助类
    /// </summary>
    public class RedisHelper
    {
        /// <summary>
        /// 初始化链接
        /// </summary>
        private static readonly ConnectionMultiplexer _con = ConnectionMultiplexer.Connect("127.0.0.1:6379");//此处写redis的账号和密码;



        #region String类型
        /// <summary>
        /// 查
        /// </summary>
        /// <param name="DataOrder">db的序号</param>
        /// <param name="Key">Key名</param> 
        public static string GetStringValue_Redis(int DataOrder, string Key)
        {
            IDatabase db = _con.GetDatabase(DataOrder);  // GetDatabase()括号中如果不填写数字就默认是0
            return db.StringGet(Key);  // 得到缓存
        }

        /// <summary>
        ///  增
        /// </summary>
        /// <param name="DataOrder">db的序号</param>
        /// <param name="Key">Key名</param>
        /// <param name="Value">Key值</param>
        /// <param name="expiry">过期时间</param>
        /// <returns></returns>
        public static async Task<bool> AddStringValue_Redis(int DataOrder, string Key, string Value, TimeSpan? expiry = null)
        {
            IDatabase db = _con.GetDatabase(DataOrder);  // GetDatabase()括号中如果不填写数字就默认是0
            if (expiry != null)
            {
                return await db.StringSetAsync(Key, Value, expiry);  // string类型存入缓存
            }
            else
            {
                return await db.StringSetAsync(Key, Value);  // string类型存入缓存
            }
        }
        #endregion
    }

三、客户端测试(MQTTX)

3.1 使用MQTTX连接broker服务器,订阅"mqttnet/samples/topic/1"主题

3.2 运行程序,观察控制台

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

笔神小卢

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

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

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

打赏作者

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

抵扣说明:

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

余额充值