Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of a C# MQTT client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
// including the M2Mqtt Library
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
MqttClient client;
string clientId;
// this code runs when the main window opens (start of the app)
public MainWindow()
{
InitializeComponent();
string BrokerAddress = "test.mosquitto.org";
client = new MqttClient(BrokerAddress);
// register a callback-function (we have to implement, see below) which is called by the library when a message was received
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
// use a unique id as client id, each time we start the application
clientId = Guid.NewGuid().ToString();
client.Connect(clientId);
}
// this code runs when the main window closes (end of the app)
protected override void OnClosed(EventArgs e)
{
client.Disconnect();
base.OnClosed(e);
App.Current.Shutdown();
}
// this code runs when the button "Subscribe" is clicked
private void btnSubscribe_Click(object sender, RoutedEventArgs e)
{
if (txtTopicSubscribe.Text != "")
{
// whole topic
string Topic = "/ElektorMyJourneyIoT/" + txtTopicSubscribe.Text + "/test";
// subscribe to the topic with QoS 2
client.Subscribe(new string[] { Topic }, new byte[] { 2 }); // we need arrays as parameters because we can subscribe to different topics with one call
txtReceived.Text = "";
}
else
{
System.Windows.MessageBox.Show("You have to enter a topic to subscribe!");
}
}
// this code runs when the button "Publish" is clicked
private void btnPublish_Click(object sender, RoutedEventArgs e)
{
if (txtTopicPublish.Text != "")
{
// whole topic
string Topic = "/ElektorMyJourneyIoT/" + txtTopicPublish.Text + "/test";
// publish a message with QoS 2
client.Publish(Topic, Encoding.UTF8.GetBytes(txtPublish.Text), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
}
else
{
System.Windows.MessageBox.Show("You have to enter a topic to publish!");
}
}
// this code runs when a message was received
void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
string ReceivedMessage = Encoding.UTF8.GetString(e.Message);
Dispatcher.Invoke(delegate { // we need this construction because the receiving code in the library and the UI with textbox run on different threads
txtReceived.Text = ReceivedMessage;
});
}
}
}
@JovanYong

This comment has been minimized.

Copy link

commented Mar 22, 2017

Hi cwschroeder , i would like to ask if it possible that your code be able to convert to web application for visual studio?

@Head-Scratcher

This comment has been minimized.

Copy link

commented Dec 5, 2017

Haven't got it displaying anything yet, but at least I have no errors with yours, which is a massive step up from most of the other code I have spent hours on time trying to get to work. Many thanks for sharing.

@Head-Scratcher

This comment has been minimized.

Copy link

commented Dec 5, 2017

Got it working :D
Issue was in the renaming of private void btnSubscribe_Click(object sender, RoutedEventArgs e) to private void BtnSubscribe_Click(object sender, RoutedEventArgs e) had to capitalize the B to make VS happy with the naming convention, but that broke the Button event. Had to recreate new buttons and it works fine.

@ccoenen

This comment has been minimized.

Copy link

commented May 21, 2018

Thanks for the example!

@PravinPravin

This comment has been minimized.

Copy link

commented Jul 14, 2018

Hi,
I have created my free trial login on azure and I want to use my own Broker address instead of test.mosquitto.org. can you please help me to set up my new broker. I am new on azure.

@SyedAkramAhmed

This comment has been minimized.

Copy link

commented Jul 27, 2018

i have created a windows application with same piece of code getting error while connecting the client.

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 37.187.106.16:1883

Any idea what to do ?

@BeginnerRaffe

This comment has been minimized.

Copy link

commented Oct 28, 2018

Hello, I got an error for this line:

        Dispatcher.Invoke(delegate {              // we need this construction because the receiving code in the library and the UI with textbox run on different threads
            txtReceived.Text = ReceivedMessage;  

"name dispatcher does not exist", what to do?

@MarkJoel60

This comment has been minimized.

Copy link

commented Dec 19, 2018

@BeginnerRaffe: Are you using WPF or Winforms? Is you are using winforms, you can replace

  Dispatcher.Invoke(delegate {              // we need this construction because the receiving code in the library and the UI with textbox run on different threads
            txtReceived.Text = ReceivedMessage; 

with:

txtReceived.Invoke((MethodInvoker)(() => txtReceived.Text = ReceivedMessage));

@monikharajs

This comment has been minimized.

Copy link

commented Jul 31, 2019

Hii, My error is Severity Code Description Project File Line Suppression State
Error CS0246 "The type or namespace name 'uPLibrary' could not be found" (are you missing a using directive or an assembly reference?) First C:\Users\Home\source\repos\First\First\MainWindow.xaml.cs 18 Active
I am using 2019 version, Can you plss say the solution for this??

@BrkDalkiran

This comment has been minimized.

Copy link

commented Aug 6, 2019

Hi Christian, i need uPLibrary same as a dll. can i use it that way

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.