【实例简介】
基于C# MQTTNet开发,Visual Studio 2017打开项目,其他版本不保证好用
【实例截图】
服务端
客户端
【核心代码】
using MQTTnet;
using MQTTnet.Core;
using MQTTnet.Core.Client;
using MQTTnet.Core.Packets;
using MQTTnet.Core.Protocol;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
namespace MqttNetClient
{
public partial class FrmMqttClient : Form
{
private MqttClient mqttClient = null;
public FrmMqttClient()
{
InitializeComponent();
Task.Run(async () => { await ConnectMqttServerAsync(); });
}
///
/// 连接服务器
///
///
private async Task ConnectMqttServerAsync()
{
if (mqttClient == null)
{
mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient;
mqttClient.ApplicationMessageReceived = MqttClient_ApplicationMessageReceived;
mqttClient.Connected = MqttClient_Connected;
mqttClient.Disconnected = MqttClient_Disconnected;
}
try
{
var options = new MqttClientTcpOptions
{
Server = ConfigurationManager.AppSettings["ServerUrl"].ToString(),//"127.0.0.1",
//Server = "10.85.5.60",
//Server = "192.168.209.243",
Port = 1883,
ClientId = ConfigurationManager.AppSettings["ClientId"].ToString(),//.Substring(0, 5),
UserName = "u001",
Password = "p001",
CleanSession = true
};
await mqttClient.ConnectAsync(options);
}
catch (Exception ex)
{
Invoke((new Action(() =>
{
txtReceiveMessage.AppendText($"连接到MQTT服务器失败!" Environment.NewLine ex.Message Environment.NewLine);
})));
}
}
///
/// 服务器连接成功
///
///
///
private void MqttClient_Connected(object sender, EventArgs e)
{
Invoke((new Action(() =>
{
txtReceiveMessage.AppendText("已连接到MQTT服务器!" Environment.NewLine);
})));
}
///
/// 断开服务器连接
///
///
///
private void MqttClient_Disconnected(object sender, EventArgs e)
{
Invoke((new Action(() =>
{
txtReceiveMessage.AppendText("已断开MQTT连接!" Environment.NewLine);
})));
}
///
/// 接收到消息
///
///
///
private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
{
Invoke((new Action(() =>
{
txtReceiveMessage.AppendText($">> {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}");
})));
}
///
/// 订阅消息
///
///
///
private void BtnSubscribe_ClickAsync(object sender, EventArgs e)
{
string topic = txtSubTopic.Text.Trim();
if (string.IsNullOrEmpty(topic))
{
MessageBox.Show("订阅主题不能为空!");
return;
}
if (!mqttClient.IsConnected)
{
MessageBox.Show("MQTT客户端尚未连接!");
return;
}
mqttClient.SubscribeAsync(new List {
new TopicFilter(topic, MqttQualityOfServiceLevel.ExactlyOnce)
});
txtReceiveMessage.AppendText($"已订阅[{topic}]主题" Environment.NewLine);
//txtSubTopic.Enabled = false;
//btnSubscribe.Enabled = false;
}
///
/// 发布主题
///
///
///
private void BtnPublish_Click(object sender, EventArgs e)
{
string topic = txtPubTopic.Text.Trim();
if (string.IsNullOrEmpty(topic))
{
MessageBox.Show("发布主题不能为空!");
return;
}
string inputString = txtSendMessage.Text.Trim();
var appMsg = new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes(inputString), MqttQualityOfServiceLevel.AtMostOnce, false);
mqttClient.PublishAsync(appMsg);
}
private void FmMqttClient_Load(object sender, EventArgs e)
{
//Dictionary dic = new Dictionary();
//dic.Add("ClientId", "123");
//dic.Add("Topic", "ttt");
//dic.Add("Value", "ggyy");
//dic.Add("ServiceLevel", "1");
//TopicLogic.SaveTopic(dic);
}
}
}