订阅消息

  • 引用的MQTTnet最新4.1.0版本,新增MqttClientService类,实例化client。然后连接到服务端后订阅topic
  1. using MQTTnet;
  2. using MQTTnet.Client;
  3. using MQTTnet.Protocol;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace MQTTClient
  9. {
  10. public class MqttClientService
  11. {
  12. public static IMqttClient _mqttClient;
  13. public IMqttClient MqttClientStart(string ip, int port, string username, string pwd, string clientId)
  14. {
  15. var optionsBuilder = new MqttClientOptionsBuilder()
  16. .WithTcpServer(ip, port) // 要访问的mqtt服务端的 ip 和 端口号
  17. .WithCredentials(username, pwd) // 要访问的mqtt服务端的用户名和密码
  18. .WithClientId(clientId) // 设置客户端id
  19. .WithCleanSession()
  20. .WithTls(new MqttClientOptionsBuilderTlsParameters
  21. {
  22. UseTls = false // 是否使用 tls加密
  23. });
  24. var clientOptions = optionsBuilder.Build();
  25. _mqttClient = new MqttFactory().CreateMqttClient();
  26. //_mqttClient.ConnectedAsync += _mqttClient_ConnectedAsync; // 客户端连接成功事件
  27. //_mqttClient.DisconnectedAsync += _mqttClient_DisconnectedAsync; // 客户端连接关闭事件
  28. //_mqttClient.ApplicationMessageReceivedAsync += _mqttClient_ApplicationMessageReceivedAsync; // 收到消息事件
  29. _mqttClient.ConnectAsync(clientOptions);
  30. return _mqttClient;
  31. }
  32. }
  33. }
  1. using MQTTnet.Client;
  2. using MQTTnet.Protocol;
  3. using System;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace MQTTClient
  7. {
  8. internal class Program
  9. {
  10. private static IMqttClient client;
  11. static void Main(string[] args)
  12. {
  13. Console.WriteLine("Hello World!");
  14. client = new MqttClientService().MqttClientStart("127.0.0.1", 1883, "cyw", "123456", "cyw");
  15. client.ConnectedAsync += Client_ConnectedAsync;
  16. client.ApplicationMessageReceivedAsync += Client_ApplicationMessageReceivedAsync;
  17. client.DisconnectedAsync += Client_DisconnectedAsync;
  18. Console.ReadLine();
  19. }
  20. private static Task Client_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
  21. {
  22. Console.WriteLine("Client_DisconnectedAsync");
  23. return Task.CompletedTask;
  24. }
  25. private static Task Client_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
  26. {
  27. Console.WriteLine($"ApplicationMessageReceivedAsync:客户端ID=【{arg.ClientId}】接收到消息。 Topic主题=【{arg.ApplicationMessage.Topic}】 消息=【{Encoding.UTF8.GetString(arg.ApplicationMessage.Payload)}】 qos等级=【{arg.ApplicationMessage.QualityOfServiceLevel}】");
  28. return Task.CompletedTask;
  29. }
  30. private static System.Threading.Tasks.Task Client_ConnectedAsync(MqttClientConnectedEventArgs arg)
  31. {
  32. client.SubscribeAsync("test", MqttQualityOfServiceLevel.AtLeastOnce);
  33. Console.WriteLine("Client_ConnectedAsync");
  34. return Task.CompletedTask;
  35. }
  36. }
  37. }