Реализация MQTTNET Клиент/Брокер
MQTTNET — это пакет NET, который реализует
допустимый протокол MQTT MQTTnet Смотреть подробные инструкции.
Реализовать клиента
using Microsoft.Extensions.Logging;
using MQTTnet;
using MQTTnet.Client.Options;
using MQTTnet.Client.Receiving;
using MQTTnet.Protocol;
using MQTTnet.Server;
using Newtonsoft.Json.Linq;
using System;
using System.Threading;
namespace clientforMqtt
{
class Program
{
static async System.Threading.Tasks.Task Main(string[] args)
{
// Create a MQTTCLIENT
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
// Create TCP Options to connect MQTT
var options = new MqttClientOptionsBuilder()
// Clinet name
.WithClientId("client1")
// MQTT Broker server address IP, the default is 1883 port
.WithTcpServer("127.0.0.1",1884)
// Hivemq login user name
.WithUserProperty("admin","hivemq")
.WithCleanSession()
.Build();
await mqttClient.ConnectAsync(options, CancellationToken.None);
Console.WriteLine("connection succeeded");
while(true)
{
Console.WriteLine("Please enter the MQTT theme TOPIC, if you quit, please enter Q");
string topic = Console.ReadLine();
if (string.Equals(topic, "Q"))
break;
Console.WriteLine("Please enter MQTT content");
string payload = Console.ReadLine();
var message = new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(payload)
.WithExactlyOnceQoS()
.WithRetainFlag()
.Build();
await mqttClient.PublishAsync(message, CancellationToken.None);
Console.WriteLine("Release Message Success");
Console.WriteLine("-----------------");
}
}
}
}
Реализовать потребительский клиент
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using System;
using System.Text;
using System.Threading;
namespace CosumeMqtt
{
class Program
{
static async System.Threading.Tasks.Task Main(string[] args)
{
// Create a MQTTCLIENT
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
// Create TCP Options to connect MQTT
var options = new MqttClientOptionsBuilder()
// Clinet name
.WithClientId("client2")
// MQTT Broker server address IP, the default is 1883 port
.WithTcpServer("127.0.0.1", 1884)
// Hivemq login user name
.WithUserProperty("admin", "hivemq")
.WithCleanSession()
.Build();
await mqttClient.ConnectAsync(options, CancellationToken.None);
Console.WriteLine("connection succeeded");
await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("mytopic").Build());
await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("hello").Build());
Console.WriteLine("Subscribe Message Success");
mqttClient.UseApplicationMessageReceivedHandler(async e =>
{
Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
Console.WriteLine();
});
Console.ReadLine();
}
}
}
Внедрить брокера MQTT
using MQTTnet;
using MQTTnet.Server;
using System;
using System.Text;
namespace MqttServer
{
class Program
{
static async System.Threading.Tasks.Task Main(string[] args)
{
var optionsBuilder = new MqttServerOptionsBuilder()
.WithConnectionBacklog(100)
.WithDefaultEndpointPort(1884);
var mqttServer = new MqttFactory().CreateMqttServer();
await mqttServer.StartAsync(optionsBuilder.Build());
Console.WriteLine("MQTT server creation success");
mqttServer.UseClientConnectedHandler(async e =>
{
Console.WriteLine("Client connection -----");
Console.WriteLine("Client ID:" + e.ClientId);
});
mqttServer.UseApplicationMessageReceivedHandler(async e =>
{
Console.WriteLine("Server-side receiving information");
Console.WriteLine("topic:" + e.ApplicationMessage.Topic);
Console.WriteLine("payload:" + Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
});
mqttServer.UseClientDisconnectedHandler(async e =>
{
Console.WriteLine("Customer is disconnected");
Console.WriteLine("Client Information ClientID:" + e.ClientId);
});
Console.ReadLine();
}
}
}
Только полноправные пользователи могут оставлять комментарии. Аутентифицируйтесь пожалуйста, используя сервисы.