2

MQTT in c#

I have two button in my xaml page. One is to Publish the message and other is to subscribe the topic. I have installed mosquitto as broker. In Publish button, i have written code to publish the message and in mosquitto cmd prompt, i can receive the message. 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?

 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.

2 Answers 2

1

The MessageStream property returns an IObservable that you are supposed to subscribe to:

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

As I understand it, you need to hook a delegate using MqttMsgPublishReceived See 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);
}

1 Comment

Yes i checked. Since it is third party dll i didnt used in my project. I am using Microsoft released libraries System.Net.Mqtt and System.Net.Mqtt.Server. There i dont find any event

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.