C# MQTT communication

Preface

MQTTnet is the net version of Mqtt. Domestic MQTTnet tutorials are relatively old and are all version 2.x. MQTTnet has major changes in the code logic of version 4.x. So in the end I still program for Github.

EMQ X introduction and installation

Long link (MQTT) testing and tool MQTTX use

MQTTnet

Insert image description here
MQTTnet Github official website

MQTTnet simple case
Insert image description here

MQTTnet is more difficult, and you need to be proficient in using the Task asynchronous method.

MQTT initial variables

//MqttClient工厂
 private MqttFactory mqttFactory = new MqttFactory();
 //MqttClient对象
 private IMqttClient mqttClient;
 //MqttClient连接选项
 private MqttClientOptions options;

Generate option


  options = new MqttClientOptionsBuilder()
  .WithTcpServer(IP地址, 端口号)
  .WithCredentials(用户名, 密码)
  .WithClientId(ClientId)
  .Build();

Connect to Mqtt server

public async Task Connect()
{
    
    
    await mqttClient.ConnectAsync(options);
    if (mqttClient.IsConnected)
    {
    
    
        Console.WriteLine("连接成功!");
    }
    SubTopics.ForEach(async item =>
    {
    
    
        await mqttClient.SubscribeAsync(item);
        Console.WriteLine($"订阅:{item}");


    });
    HMACSHA256("fa34e04e-43b2-5309-817d-953e9576a07d", "2020050617");
    Console.WriteLine("服务器连接成功!");



}

send data

        /// <summary>
        /// 发送
        /// </summary>
        public Task Send(string topic, object payload)
        {
    
    
            var msg = new MqttApplicationMessageBuilder()
            .WithTopic(topic)
            .WithPayload(JsonConvert.SerializeObject(payload))
            .Build();
            Console.WriteLine("发送信息");
            Console.WriteLine($"{topic}");

            Console.WriteLine($"{JsonConvert.SerializeObject(payload)}");
            return mqttClient.PublishAsync(msg);
        }

Add subscription

//订阅事件
await mqttClient.SubscribeAsync(item);

//订阅事件消息接收
mqttClient.ApplicationMessageReceivedAsync += e =>
            {
    
    
                Console.WriteLine("收到消息");
                Console.WriteLine($"Topic:{
      
      e.ApplicationMessage.Topic}");
                Console.WriteLine($"Message:{
      
      e.ApplicationMessage.ConvertPayloadToString()}");

                return Task.CompletedTask;
            };

What we usually mainly do is the client. For details, please see the MQTTnet client Github example.

Insert image description here

Guess you like

Origin blog.csdn.net/qq_44695769/article/details/133348525