1、新建一个控制台项目
2、设置项目名称、位置、.net框架
3、将proto文件放到项目根目录并包含在项目中
4、去Protogen官网将.proto文件在线生成C#类文件:https://protogen.marcgravell.com/
1)选择CSharp
2)复制粘贴mqtt.proto文件内容到左边,点击Generate
5、在C#中新建cs文件并将右边内容复制粘贴到cs文件中
6、添加protobuf-net包(3.2.30版本)和MQTTnet包(4.3.6.1152版本)
7、编写业务类(附上代码)
public static void MetatagRetain()
{
Console.WriteLine("======设备主动上送位号数据======");
#region 连接位号数据MQTT服务器
// 创建MQTT客户端
var mqttClient = new MqttFactory().CreateMqttClient();
// 创建连接选项
var options = new MqttClientOptionsBuilder()
.WithTcpServer(ip, port) // MQTT代理地址和端口
.WithClientId(endpointId)//客户端id
.WithCleanSession()//清空缓存
.Build();
var con = mqttClient.ConnectAsync(options);
if (con.Result.ResultCode == MqttClientConnectResultCode.Success)
{
// MQTT服务器连接成功
Console.WriteLine("位号数据MQTT服务器连接成功!");
}
else
{
// MQTT服务器连接失败
Console.WriteLine("位号数据MQTT服务器连接失败!" + con.Result.ResultCode);
}
#endregion
var message = ProtobufferTool.ToBytes("message");
string topic = "topic";
Task.Run(async () =>
{
//发布消息(QOS = 0:至多一次, QOS = 1:至少一次, QOS = 2:只有一次)
var response = await mqttClient.PublishAsync(new MqttApplicationMessageBuilder()
.WithTopic(topic) // 主题
.WithPayload(message)//消息体
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce)//QOS = 0
.WithRetainFlag(true)//启用消息的保留标志Reatin = 1
.Build());
if (response.ReasonCode == MqttClientPublishReasonCode.Success)
{
// 消息成功发布
Console.WriteLine("位号数据推送成功!");
}
else
{
// 消息发布失败,result.ReasonCode会提供具体原因
Console.WriteLine("位号数据推送失败!Message:" + response.ReasonCode);
}
});
}
8、ProtoBuff序列化和反序列化(附上代码)
using System;
using System.IO;
using ProtoBuf;
namespace MQTTClientTest
{
public static class ProtobufferTool
{
// 序列化
public static byte[] ToBytes(object obj)
{
try
{
using (MemoryStream ms = new MemoryStream())
{
Serializer.Serialize(ms, obj);
var buffer = ms.GetBuffer();
var dataBuffer = new byte[ms.Length];
Array.Copy(buffer, dataBuffer, ms.Length);
ms.Dispose();
return dataBuffer;
}
}
catch
{
return null;
}
}
// 反序列化
public static T ToObj<T>(byte[] bufferData)
{
if (bufferData == null)
{
return default;
}
try
{
using (MemoryStream ms = new MemoryStream())
{
ms.SetLength(bufferData.Length);
ms.Write(bufferData, 0, bufferData.Length);
ms.Position = 0L;
ms.Flush();
T result = Serializer.Deserialize<T>(ms);
ms.Dispose();
return result;
}
}
catch
{
return default;
}
}
}
}
9、调用业务方法