简体   繁体   English

调用mqtt异步方法时如何接收已发布的消息

[英]How to receive published message when mqtt async method called

MQTT in c# C# 中的 MQTT

I have two button in my xaml page.我的 xaml 页面中有两个按钮。 One is to Publish the message and other is to subscribe the topic.一种是发布消息,另一种是订阅主题。 I have installed mosquitto as broker.我已经安装了 mosquitto 作为代理。 In Publish button, i have written code to publish the message and in mosquitto cmd prompt, i can receive the message.在发布按钮中,我编写了代码来发布消息,在 mosquitto cmd 提示中,我可以接收消息。 In viceversa, in subscribe button, i have subscribed to one topic and in cmd prompt i am publishing message, where can i view the message in subscribe button?反之亦然,在订阅按钮中,我订阅了一个主题,在 cmd 提示中我正在发布消息,我可以在哪里查看订阅按钮中的消息?

 Case 1:       
    In cmd propmt, i will subscribe to the topic,
    mosquitto_sub -h 190.178.4.180 -t “test1”  

    private async void BtnPublish_Click(object sender, RoutedEventArgs e)
    {     
        var message = new MqttApplicationMessage("test1", Encoding.UTF8.GetBytes("Hello"));

        await client.PublishAsync(message, MqttQualityOfService.ExactlyOnce);
    }

    I will receive Hello in cmd propmt.

 Case 2:

    In cmd prompt, i will publish the message in some topic,
    mosquitto_pub -h 192.168.0.180 -t test1 -m "HelloWorld"

    private async void BtnSubscrbe_Click(object sender, RoutedEventArgs e)
    {
        await client.SubscribeAsync("test1", MqttQualityOfService.ExactlyOnce);
        var message = client.MessageStream;
    } 

 If i click the button subscribe, where will i get the published message?

Thanks in advance.提前致谢。

The MessageStream property returns an IObservable that you are supposed to subscribe to: MessageStream属性返回一个您应该订阅的IObservable

private async void BtnSubscrbe_Click(object sender, RoutedEventArgs e)
{
    client.MessageStream.Subscribe(msg =>
    {
        string topic = msg.Topic;
        byte[] payload = msg.Payload;
        //deserialize and do something...
    });

    await client.SubscribeAsync("test1", MqttQualityOfService.ExactlyOnce);
}

As I understand it, you need to hook a delegate using MqttMsgPublishReceived See https://www.hivemq.com/blog/mqtt-client-library-encyclopedia-m2mqtt/据我了解,您需要使用 MqttMsgPublishReceived 来挂钩委托,请参阅https://www.hivemq.com/blog/mqtt-client-library-encyclopedia-m2mqtt/

client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

and

void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
     Debug.WriteLine("Received = " + Encoding.UTF8.GetString(e.Message) + " on topic " + e.Topic);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM