我正在尝试使用C#应用程序从mqtt代理订阅

时间:2019-06-21 06:17:59

标签: c# mqtt

您好,我从paho客户端向MQTT代理发布了一条消息,并希望使用该主题来订阅该消息;我的问题是调试器出现在client端时。MqttMsgPublishReceived+ = client_MqttMsgPublishReceived;它没有执行该方法并移至下一行。

我使用带有M2MQTT库的蜂巢mqtt代理和c#表单应用程序。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;

// including the M2Mqtt Library
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;

private void button1_Click(object sender, EventArgs e)
{
  MqttClient client = new MqttClient("192.168.43.51");
  client.ProtocolVersion = MqttProtocolVersion.Version_3_1;
  byte code = client.Connect(Guid.NewGuid().ToString());
  ushort msgIds = client.Subscribe(new string[] { @"Factory1\Sensor1" },
                    new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
  textBox1.Text = "";
  client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
}
void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
  this.Invoke((MethodInvoker)delegate ()
  {
    textBox1.Text += "Received = " + Encoding.UTF8.GetString(e.Message) + " 
    on topic " + e.Topic + "\r\n";
  });
}

我想在文本框中获取发布的消息。你们能帮我吗? 谢谢。

1 个答案:

答案 0 :(得分:0)

  

我的问题是调试器出现在client.MqttMsgPublishReceived + = client_MqttMsgPublishReceived;中。它没有执行该方法并移至下一行。

此行不应执行该方法,因为它仅连接事件处理程序。相反,当client_MqttMsgPublishReceived类引发MqttClient事件时(接收到MQTT消息时),将调用事件处理程序MqttMsgPublishReceived中的代码。

您可以通过在client_MqttMsgPublishReceived函数中添加断点并将消息发布到Factory1\Sensor1主题来看到此情况。您可以使用单独的MQTT客户端来发布此消息。 (请注意,MQTT主题分隔符是正斜杠“ /”,因此您需要将其发布到带有反斜杠的主题。)

有关如何订阅事件的概述,请参见https://docs.microsoft.com/en-us/dotnet/standard/events/#event-handlers