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