首先通过neget安装M2mqtt
//首先在类里开头实例化mqtt
private MqttClient client;
/// <summary>
/// intopic传入的topic 以及需要回调的方法
/// </summary>
/// <param name="intopic"></param>
/// <param name="callback"></param>
private void createClient(string intopic,Action<object, MqttMsgPublishEventArgs> callback)
{
try
{
int mqttport = Convert.ToInt32(AccessAppSettings("MqttAddressPort"));
//这里的 ip地址以及端口是写在app.config里配置的
client = new MqttClient(IPAddress.Parse(ConfigurationManager.AppSettings["MqttAddress"]), mqttport, false, null, null, MqttSslProtocols.TLSv1_2);
//创建客户端实例(两种方式选择,否则出错,域名需转换)
client.ProtocolVersion = (MqttProtocolVersion)mqttport;
//2.为MqttMsgPublishReceived 事件绑定方法,当订阅到消息时执行callBack委托方法
client.MqttMsgPublishReceived += (sender, e) =>
{
callback.Invoke(sender, e);
};
client.Connect(mac, AccessAppSettings("MqttUser"), AccessAppSettings("MqttPassword"));
// 绑定mqtt断链时间
client.ConnectionClosed += delegate
{
Task.Factory.StartNew(() =>
{
while (client == null || client.IsConnected == false)
{
Task.Delay(5 * 1000);
//topic 是我这边需要增加的参数 具体需求看自己
string topic = AccessAppSettings("MqttTopic") + mac;
createClient(topic, callback);
SubTopic(topic, callback);
}
}).ConfigureAwait(false);
};
}
catch(Exception e)
{
}
}
//订阅,省略了判断步骤,保留核心代码 参数 传入的topic 以及需要回调的方法
public void SubTopic(string topic, Action<object, MqttMsgPublishEventArgs> callBack)
{
//创建客户端并连接代理
createClient(topic,callBack);
//订阅主题
client.Subscribe(new string[] { topic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
}
//从这里写处理接受到消息后的逻辑代码
void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
//处理接收到的消息
}
在需要调用mqtt的地方
SubTopic(需要传入的topic,需要回调的方法就是处理接受到消息后的逻辑代码)