发送消息

  • 引用的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 MQTTPublish
  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;
  2. using MQTTnet.Client;
  3. using MQTTnet.Protocol;
  4. using MQTTnet.Server;
  5. using System;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace MQTTPublish
  9. {
  10. internal class Program
  11. {
  12. private static IMqttClient client;
  13. static void Main(string[] args)
  14. {
  15. Console.WriteLine("Hello World!");
  16. client = new MqttClientService().MqttClientStart("127.0.0.1", 1883, "cyw", "123456", "cywcyw");
  17. client.ConnectedAsync += Client_ConnectedAsync;
  18. Console.ReadLine();
  19. }
  20. private static System.Threading.Tasks.Task Client_ConnectedAsync(MqttClientConnectedEventArgs arg)
  21. {
  22. Console.WriteLine("Client_ConnectedAsync");
  23. var message = new MqttApplicationMessage
  24. {
  25. Topic = "test",
  26. Payload = Encoding.Default.GetBytes("cyw-123456"),
  27. QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
  28. Retain = true // 服务端是否保留消息。true为保留,如果有新的订阅者连接,就会立马收到该消息。
  29. };
  30. Console.WriteLine("PublishAsync topic:"+ message.Topic+ " Payload:"+ Encoding.UTF8.GetString(message.Payload));
  31. client.PublishAsync(message);
  32. return Task.CompletedTask;
  33. }
  34. }
  35. }