文章目录
- 前言
- MQTTnet
- MQTT初始变量
- 生成option
- 连接Mqtt服务器
- 发送数据
- 添加订阅
前言
MQTTnet是Mqtt的net版本。国内MQTTnet教程比较老旧,都是2.x版本。MQTTnet在4.x版本版本代码逻辑有比较大的改动。所以最后还是面向Github编程。
EMQ X介绍及安装
长链接(MQTT)测试及工具MQTTX使用
MQTTnet
MQTTnet Github官网
MQTTnet简单案例
MQTTnet比较难,要熟练掌握Task异步方法的使用。
MQTT初始变量
//MqttClient工厂
private MqttFactory mqttFactory = new MqttFactory();
//MqttClient对象
private IMqttClient mqttClient;
//MqttClient连接选项
private MqttClientOptions options;
生成option
options = new MqttClientOptionsBuilder()
.WithTcpServer(IP地址, 端口号)
.WithCredentials(用户名, 密码)
.WithClientId(ClientId)
.Build();
连接Mqtt服务器
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("服务器连接成功!");
}
发送数据
/// <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);
}
添加订阅
//订阅事件
await mqttClient.SubscribeAsync(item);
//订阅事件消息接收
mqttClient.ApplicationMessageReceivedAsync += e =>
{
Console.WriteLine("收到消息");
Console.WriteLine($"Topic:{e.ApplicationMessage.Topic}");
Console.WriteLine($"Message:{e.ApplicationMessage.ConvertPayloadToString()}");
return Task.CompletedTask;
};
我们一般主要做的是客户端,详情请看MQTTnet 客户端Github示例