1 . 搭建MQTT服务器
找到上传中的 emqx-5.3.2-windows-amd64 打开bin如下:
链接: emqx-5.3.2-windows-amd64
如果安装失败 在上传中找到链接: VC_redist.x64.exe 安装。
正确后在浏览器输入 http://127.0.0.1:18083 会有如下mqtt服务端管理页面:
进入客户端认证,创建一个服务端池。里面设置用户名密码。
c# 中 mqtt 客户端端口用 ip :1883
websoket 端口用 8083
c# 客户端连接
管理NuGet程序包 添加mqttnet
界面
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.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private MqttClient mqttClient = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{}
//连接方法
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 = textBox5.Text,// "172.16.6.133",
Port =Convert.ToInt32(textBox7.Text),// 1883,
ClientId = Guid.NewGuid().ToString().Substring(0, 5),//这个只要不重复就行
UserName = textBox3.Text,// "yado",
Password = textBox6.Text // "yado123"
};
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 button3_Click(object sender, EventArgs e)
{
Task.Run(async () => { await ConnectMqttServerAsync(); });
}
//发布主题
private void button1_Click(object sender, EventArgs e)
{
try
{
string topic = textBox1.Text.Trim();
if (string.IsNullOrEmpty(topic))
{
MessageBox.Show("发布主题不能为空!");
return;
}
string inputString = textBox2.Text.Trim();
var appMsg = new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes(inputString), MqttQualityOfServiceLevel.AtMostOnce, false);
mqttClient.PublishAsync(appMsg);
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
//订阅
private void button2_Click(object sender, EventArgs e)
{
string topic = textBox4.Text.Trim();
if (string.IsNullOrEmpty(topic))
{
MessageBox.Show("订阅主题不能为空!");
return;
}
if (!mqttClient.IsConnected)
{
MessageBox.Show("MQTT客户端尚未连接!");