使用winforms实现一个mqtt的客户端程序
创建项目
确定项目的框架是.net Framework 4.8的,
引用包
打开包管理器控制台
输入Install-Package M2Mqtt
安装依赖
或者
搭建UI框架
拖拽三个按钮
名字分别是:
btnConnectionMqttServer
btnDisConnectionMqttServer
btnSendDate
代码编写
双击按钮添加点击事件,并填写代码
using System;
using System.Windows.Forms;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace MqttConnectinTest
{
public partial class Form1 : Form
{
/// <summary>
/// MQTT连接
/// </summary>
private MqttClient mqttClient;
public Form1()
{
InitializeComponent();
InitializeMqttClient();
btnConnectionMqttServer.Enabled = true;
btnDisConnectionMqttServer.Enabled = false;
}
/// <summary>
/// 初始初始化mqtt连接
/// </summary>
private void InitializeMqttClient()
{
// 创建 MQTT 客户端实例
mqttClient = new MqttClient("broker.emqx.io"); // 替换为你的 MQTT 代理地址
// 注册连接事件处理程序
mqttClient.MqttMsgPublishReceived += MqttClient_MqttMsgPublishReceived;
//设置mqtt版本
mqttClient.ProtocolVersion = MqttProtocolVersion.Version_3_1_1;
}
private void btnConnectionMqttServer_Click(object sender, EventArgs e)
{
// 连接到 MQTT 代理
string clientId = Guid.NewGuid().ToString();
mqttClient.Connect(clientId);
if (mqttClient.IsConnected)
{
MessageBox.Show("Connected to MQTT broker!");
// 订阅主题
mqttClient.Subscribe(new string[] { "test/topic/wyh123456" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });
btnConnectionMqttServer.Enabled = false;
btnDisConnectionMqttServer.Enabled = true;
}
else
{
MessageBox.Show("Failed to connect to MQTT broker!");
}
}
private void btnDisConnectionMqttServer_Click(object sender, EventArgs e)
{
if (mqttClient != null && mqttClient.IsConnected)
{
mqttClient.Disconnect();
MessageBox.Show("Disconnected from MQTT broker.");
btnConnectionMqttServer.Enabled = true;
btnDisConnectionMqttServer.Enabled = false;
}
}
private void btnSendDate_Click(object sender, EventArgs e)
{
string message = "发送数据:" + DateTime.Now.ToString();
mqttClient.Publish("test/topic/send/wyh123456", System.Text.Encoding.UTF8.GetBytes(message));
}
private void MqttClient_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
// 处理接收到的消息
string receivedMessage = System.Text.Encoding.UTF8.GetString(e.Message);
MessageBox.Show($"Received message: {receivedMessage}");
}
}
}
测试连接
使用mqttx订阅
主题: test/topic/wyh123456
主题: test/topic/send/wyh123456
在mqttx上使用test/topic/wyh123456发送消息可以在winforms上收到,
点击windorms上的发送数据,mqtt订阅的 test/topic/send/wyh123456 主题会显示对应的消息