Skip to content

Instantly share code, notes, and snippets.

@nikvoronin
Last active January 3, 2021 21:48
Show Gist options
  • Save nikvoronin/dc7cc266bf0c7f77351b484cb530d836 to your computer and use it in GitHub Desktop.
Save nikvoronin/dc7cc266bf0c7f77351b484cb530d836 to your computer and use it in GitHub Desktop.
MQTTnet Test Queue Reader
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using System;
using System.Threading.Tasks;
namespace Tc3_DataAgentConsole
{
class Program
{
const string MQTT_BROKER_URL = "broker.hivemq.com";
//const string MQTTBROKER_URL = "test.mosquitto.org";
//const string MQTT_TOPIC = "GOT/TWINCAT/#";
public static async Task Main()
{
var factory = new MqttFactory();
var client = factory.CreateMqttClient();
var options = new MqttClientOptionsBuilder()
.WithTcpServer(MQTT_BROKER_URL)
.WithCleanSession()
.Build();
var topicFilter = new MqttTopicFilterBuilder()
.WithTopic(MQTT_TOPIC)
.Build();
client.UseApplicationMessageReceivedHandler(e => {
string message = e.ApplicationMessage.ConvertPayloadToString();
Console.WriteLine($">>> {message}");
});
client.UseDisconnectedHandler(e => {
Console.WriteLine("(-) Disconnected");
});
client.UseConnectedHandler(async e => {
Console.WriteLine("(+) Connected to server");
await client.SubscribeAsync(topicFilter);
Console.WriteLine($"[s] Subscribed to the topic `{MQTT_TOPIC}`");
});
try {
await client.ConnectAsync(options);
}
catch (Exception e) {
Console.WriteLine($"[e] {e.Message}");
}
Console.WriteLine("[i] Press [Enter] to close...");
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment