MQTT初使用
项目中涉及到了TCP通信,在别人建议下使用封装好的mqtt包实现。
在VS nuget包管理里直接搜就能找到mqtt的各种包,我这里使用的是2.8.2版本的MQTTnet
直接上代码
public async void MqttClient()
{
if (!mqttIsConnected)
{
try
{
//连接配置
var options = new MqttClientOptions() { ClientId = Guid.NewGuid().ToString("D") };
options.ChannelOptions = new MqttClientTcpOptions()
{
Server = "***.***.***.***",
Port = *****
};
options.Credentials = new MqttClientCredentials()
{
Username = "admin",
Password = "password"
};
options.CleanSession = true;
options.KeepAlivePeriod = TimeSpan.FromSeconds(100.5);
options.KeepAliveSendInterval = TimeSpan.FromSeconds(20000);
if (null != _mqttClient)
{
await _mqttClient.DisconnectAsync();
_mqttClient = null;
}
_mqttClient = new MqttFactory().CreateMqttClient();
_mqttClient.ApplicationMessageReceived += (sender, args) =>
{
Debug.Log($"ClientID:{args.ClientId} | TOPIC:{args.ApplicationMessage.Topic} | Payload:{Encoding.UTF8.GetString(args.ApplicationMessage.Payload)} | QoS:{args.ApplicationMessage.QualityOfServiceLevel} | Retain:{args.ApplicationMessage.Retain}");
};
_mqttClient.Connected += (sender, args) =>
{
Debug.Log($"Client is Connected: IsSessionPresent:{args.IsSessionPresent}");
};
_mqttClient.Disconnected += (sender, args) =>
{
Debug.Log($"Client is DisConnected ClientWasConnected:{args.ClientWasConnected}");
};
await _mqttClient.ConnectAsync(options);
mqttIsConnected = true;
try
{
await Task.Factory.StartNew(async () =>
{
await _mqttClient.SubscribeAsync(
new List<TopicFilter>
{
new TopicFilter(
"test",//订阅主题
(MqttQualityOfServiceLevel)
Enum.Parse(typeof (MqttQualityOfServiceLevel),"0"))
}) ;
});
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
}
public async void ClientStop()
{
if (mqttIsConnected)
{
if (null != _mqttClient && _mqttClient.IsConnected)
{
await _mqttClient.DisconnectAsync();
_mqttClient.Dispose();
_mqttClient = null;
mqttIsConnected = false;
Debug.Log(“Disconnected”);
}
}
}