Mqtt使用c#发布/订阅

时间:2015-11-09 06:19:02

标签: c# mqtt windows-applications mosquitto paho

我已经在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"

2 个答案:

答案 0 :(得分:1)

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

M2Mqtt客户端也可以在Nuget上作为包使用: https://www.nuget.org/packages/M2Mqtt/

保罗。

答案 1 :(得分:0)

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

连接字符串

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