承继上篇文章:基于MQTTnet 3.1组件的MQTT协议应用开发示例(1)
上篇讲到基于MQTTnet的MQTT服务端和客户端搭建,并介绍了客户端登录MQTT服务端建立通信连接的过程。这篇继续介绍消息的订阅、发布等处理。
0、引用对象
using MQTTnet.Client;
using MQTTnet;
using System;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MQTTnet.Client.Options;
using System.Threading;
1、订阅主题
private async Task Subscribe()
{
string topic = txtSubTopic.Text.Trim();
if (string.IsNullOrEmpty(topic))
{
MessageBox.Show("订阅主题不能为空!");
return;
}
if (!mqttClient.IsConnected)
{
MessageBox.Show("MQTT客户端尚未连接!");
return;
}
// Subscribe to a topic
await mqttClient.SubscribeAsync(new TopicFilterBuilder()
.WithTopic(topic)
.WithAtMostOnceQoS()
.Build()
);
Invoke((new Action(() =>
{
txtReceiveMessage.AppendText($"已订阅[{topic}]主题{Environment.NewLine}");
})));
}
2、发布主题
private async Task Publish()
{
string topic = txtPubTopic.Text.Trim();
if (string.IsNullOrEmpty(topic))
{
MessageBox.Show("发布主题不能为空!");
return;
}
string inputString = txtSendMessage.Text.Trim();
try
{
var message = new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(inputString)
.WithExactlyOnceQoS()
.WithRetainFlag()
.Build();
await mqttClient.PublishAsync(message);
}
catch (Exception ex)
{
Invoke((new Action(() =>
{
txtReceiveMessage.AppendText($"发布主题失败!" + Environment.NewLine + ex.Message + Environment.NewLine);
})));
}
}
3、退出登录
private void btnLogout_Click(object sender, EventArgs e)
{
isReconnect = false;
Task.Run(async () => { await mqttClient.DisconnectAsync(); });
Invoke((new Action(() =>
{
txtReceiveMessage.Clear();
DateTime curTime = new DateTime();
curTime = DateTime.UtcNow;
txtReceiveMessage.AppendText($">> [{curTime.ToLongTimeString()}]");
txtReceiveMessage.AppendText("已断开MQTT连接!" + Environment.NewLine);
})));
}