I am using MQTT client library from this link
https://www.hivemq.com/blog/mqtt-client-library-encyclopedia-m2mqtt/
My sample code is as follows :-
public partial class Form1 : Form
{
MqttClient client = null;
public Form1()
{
InitializeComponent();
client = new MqttClient("broker.hivemq.com");
byte code = client.Connect("lenovofullondude");
}
private void button1_Click(object sender, EventArgs e)
{
client = new MqttClient("broker.hivemq.com");
byte code = client.Connect("lenovofullondude");
client.ProtocolVersion = MqttProtocolVersion.Version_3_1;
client.MqttMsgPublished += client_MqttMsgPublished;
ushort msgId = client.Publish("/my_topic", // topic
Encoding.UTF8.GetBytes("MyMessageBody"), // message body
MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, // QoS level
false);
}
void client_MqttMsgPublished(object sender, MqttMsgPublishedEventArgs e)
{
Debug.WriteLine("MessageId = " + e.MessageId + " Published = " + e.IsPublished);
}
void client_MqttMsgSubscribed(object sender, MqttMsgSubscribedEventArgs e)
{
Debug.WriteLine("Subscribed for id = " + e.MessageId);
}
private void button2_Click(object sender, EventArgs e)
{
try
{
client = new MqttClient("broker.hivemq.com");
byte code = client.Connect("lenovofullondude");
client.ProtocolVersion = MqttProtocolVersion.Version_3_1;
client.MqttMsgSubscribed += Client_MqttMsgSubscribed;
client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
ushort msgId = client.Subscribe(new string[] { "/my_topic" },
new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
}
catch (Exception H)
{
}
}
private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
Debug.WriteLine("Received = " + Encoding.UTF8.GetString(e.Message) + " on topic " + e.Topic);
}
private void Client_MqttMsgSubscribed(object sender, MqttMsgSubscribedEventArgs e)
{
Debug.WriteLine("Subscribed for id = " + e.MessageId);
}
}
The code works as follows :-
I have 2 buttons on my application when I click button 1 it publishes the message. clicking on button 2 is expected to subscribe and receive the published message through MQTT via this handler Client_MqttMsgPublishReceived.
Problem:- Button 1 click is working fine but clicking on button 2 the subscribing is working fine but it is not receiving the published message.
Can anyone suggest what I am doing wrong. And I am just curious that my current application publishes and receives the message on Topic (using the same code).
Is it possible to make two different Application .One application will publish to Topic. And Second Appication will receive message on that Topic (Since it is subscriber)