Mqtt使用c#发布/订阅

本文关键字:订阅 发布 使用 Mqtt | 更新日期: 2023-09-27 18:21:19

我已经在Java中使用过mqtt。现在我需要创建一个C#应用程序来订阅和发布mqtt消息。

使用MqttDotNet库

IMqtt _client = MqttClientFactory.CreateClient(connectionString, clientId);

什么是connectionString

使用M2Mqtt库

连接成功,但我没有收到任何已发布的消息。

这是我的代码:

class Program
{
    static void Main(string[] args)
    {
        var client = new MqttClient(IPAddress.Parse("myTestIP"));
        // register to message received
        client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
        var clientId = Guid.NewGuid().ToString();
        client.Connect(clientId);
        // subscribe to the topic "/home/temperature" with QoS 2
        client.Subscribe(
            new string[] {"testTopic"},
            new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
    }
    static void client_MqttMsgPublishReceived(
        object sender, MqttMsgPublishEventArgs e)
    {
        // handle message received
        Console.WriteLine("message=" + e.Message.ToString());
    }
}

这是我的消息发布代码:

mosquitto_pub -d -h testIp  -t "testTopic" -m "haai"

Mqtt使用c#发布/订阅

我认为MqttDotNet目前没有维护。我可以建议使用我的M2Mqtt客户端,并在官方网站上找到文档:https://m2mqtt.wordpress.com/

M2Mqtt客户端也可在Nuget上作为软件包提供,如下所示:https://www.nuget.org/packages/M2Mqtt/

保罗。

连接字符串是(根据Steven Lovegroves网站上的示例代码文档http://www.stevenlovegrove.com/?id=37):

连接字符串

  • TCP连接,例如。tcp://brokerhost.com:1883
  • 蓝牙连接,例如bt://00:10:dc:af:66:48