C#使用M2Mqtt库进行MQTT简单通讯

本文介绍了如何使用C#中的M2Mqtt库进行MQTT通信,包括连接、发布和订阅主题的操作。通过M2Mqtt库,可以方便地发送和接收MQTT消息,同时在小工具界面上展示接收到的消息。

M2Mqtt库资源

一开始有查找Mqttnet的源码,但是比较乱,编译不过去,后来选择了M2Mqtt。源码清晰简洁,使用靠谱。
1、M2Mqtt 下载代码自己生成一下就可以在BIN文件夹里面找到相关的库。
2、在NuGet库里面直接查找M2Mqtt也可以安装库。

MQTT连接

public MqttClient mqttClient { get; set; }
private static string EMQX_BROKER_IP = "192.168.10.165";
private static int EMQX_BROKER_PORT = 1884;
// 建立MQTT连接
private void mqttConnect()
        {
            EMQX_CLIENT_ID = Guid.NewGuid().ToString();
            try
            {
                //建立连接
                mqttClient = new MqttClient(EMQX_BROKER_IP, EMQX_BROKER_PORT, false, null, null, MqttSslProtocols.TLSv1_2);
                //下面这种方法是个坑,并不能正常访问到MQTT服务器
                // mqttClient = new MqttClient(IPAddress.Parse(EMQX_BROKER_IP));
                mqttClient.Connect(EMQX_CLIENT_ID);
                mqttClient.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
                connectbtn.BackColor = Color.Green;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }
        //这段定义了收到消息之后做什么事情
        private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            string topic = e.Topic.ToString();
            string message = System.Text.Encoding.Default.GetString(e.Message);
            //同时订阅两个或者以上主题时,分类收集收到的信息
            if (topic == subscribetopictxt.Text)
            {
                messageArray.Add(message);
            }
            if (topic == subscribetopictxt1.Text)
            {
                messageArray1.Add(message);
            }
            //reciveTopic.Text = topic;
            //reciveMessagetxt.Text = message;

        }

MQTT主题发布–发消息

public void publishTopic(string currentTopic, string content)
        {            
            if (mqttClient != null && !string.IsNullOrEmpty(currentTopic) && !string.IsNullOrEmpty(content))
            {
                mqttClient.Publish(currentTopic, System.Text.Encoding.UTF8.GetBytes(content), qos, true);
            }
        }

MQTT订阅主题–收消息

 private void subscribebtn_Click(object sender, EventArgs e)
        {
            mqttClient.Subscribe(new string[] { subscribetopictxt.Text }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });

        }

小工具界面

在这里插入图片描述
同时发布了两个主题,然后订阅两个主题。分别收两个主题的消息并显示出来。
收到消息后存起来,显示的时候另外起定时器去扫才能正常显示。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值