MQTT通信
前段时间刚做了一个项目,是使用MQTT进行传输的案例,有必要在这里分享一下MQTT的通信code,直接上code,解析
首先MQTT有专属的库文件,网上百度导入工程下,接着就是两个核心东西,发送和订阅消息
1)不管发送还是订阅,前提都是先建立数据传输通道
//创建MQTT连接参数(准备工作)
var options = new MqttClientOptionsBuilder()
.WithTcpServer("www,baidu.com", 1888)
.WithCredentials("account", "psd")
.WithClientId("123456") // Port is optional
.Build();
2)建立一个通信容器,有MqttFactory专门创建
//创建MQTT连接容器(准备工作)
var factory = new MqttFactory();
var mqttClient = factory.CreateManagedMqttClient();
mqttClient.StartAsync(new ManagedMqttClientOptions
{
ClientOptions = options
});
3)利用MQTT去发送消息
Invoke((new Action(() =>
{
var message = new MqttApplicationMessageBuilder()
.WithTopic("topic")
.WithPayload("1234")
.WithExactlyOnceQoS()
.WithRetainFlag()
.Build();
mqttClient.PublishAsync(message);
Thread.Sleep(3000);//加不加都行,这里方便测试的
Console.WriteLine("sentMessage");//加不加都行,这里方便测试的
})));
4)利用MQTT去发送消息
Invoke((new Action(() =>
{
mqttClient.SubscribeAsync("topic头格式/#");//表示收所有的topic
mqttClient.UseApplicationMessageReceivedHandler(ee =>
{
Invoke((new Action(() =>
{
if (ee.ApplicationMessage.Payload != null)
{
txtReceiveMessage.Text = $"收到订阅消息!" + Encoding.UTF8.GetString(ee.ApplicationMessage.Payload);
}
})));
});
})));
我还是认为通过code去看code更容易理解语句的意思,一开始大量看博客还是一知半解