mirror of
https://github.com/dotnet/MQTTnet.git
synced 2026-10-16 01:03:01 +08:00
84 lines
2.8 KiB
C#
84 lines
2.8 KiB
C#
// Licensed to the .NET Foundation under one or more agreements.
|
|
// The .NET Foundation licenses this file to you under the MIT license.
|
|
// See the LICENSE file in the project root for more information.
|
|
|
|
// ReSharper disable UnusedType.Global
|
|
// ReSharper disable UnusedMember.Global
|
|
// ReSharper disable InconsistentNaming
|
|
|
|
using MQTTnet.Client;
|
|
using MQTTnet.Samples.Shared;
|
|
|
|
namespace MQTTnet.Samples.Client;
|
|
|
|
public static class Client_Subscribe_Samples
|
|
{
|
|
public static async Task Handle_Received_Application_Message()
|
|
{
|
|
/*
|
|
* This sample subscribes to a topic and processes the received message.
|
|
*/
|
|
|
|
var mqttFactory = new MqttFactory();
|
|
|
|
using (var mqttClient = mqttFactory.CreateMqttClient())
|
|
{
|
|
var mqttClientOptions = new MqttClientOptionsBuilder()
|
|
.WithTcpServer("broker.hivemq.com")
|
|
.Build();
|
|
|
|
// Setup message handling before connecting so that queued messages
|
|
// are also handled properly. When there is no event handler attached all
|
|
// received messages get lost.
|
|
mqttClient.ApplicationMessageReceivedAsync += e =>
|
|
{
|
|
Console.WriteLine("Received application message.");
|
|
e.DumpToConsole();
|
|
|
|
return Task.CompletedTask;
|
|
};
|
|
|
|
await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
|
|
|
|
var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder()
|
|
.WithTopicFilter(f => { f.WithTopic("mqttnet/samples/topic/2"); })
|
|
.Build();
|
|
|
|
await mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None);
|
|
|
|
Console.WriteLine("MQTT client subscribed to topic.");
|
|
|
|
Console.WriteLine("Press enter to exit.");
|
|
Console.ReadLine();
|
|
}
|
|
}
|
|
|
|
public static async Task Subscribe_Topic()
|
|
{
|
|
/*
|
|
* This sample subscribes to a topic.
|
|
*/
|
|
|
|
var mqttFactory = new MqttFactory();
|
|
|
|
using (var mqttClient = mqttFactory.CreateMqttClient())
|
|
{
|
|
var mqttClientOptions = new MqttClientOptionsBuilder()
|
|
.WithTcpServer("broker.hivemq.com")
|
|
.Build();
|
|
|
|
await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
|
|
|
|
var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder()
|
|
.WithTopicFilter(f => { f.WithTopic("mqttnet/samples/topic/1"); })
|
|
.Build();
|
|
|
|
var response = await mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None);
|
|
|
|
Console.WriteLine("MQTT client subscribed to topic.");
|
|
|
|
// The response contains additional data sent by the server after subscribing.
|
|
response.DumpToConsole();
|
|
}
|
|
}
|
|
} |