C# 实现MQTT通讯

环境

VS:.NET Framework 4.8

NuGet:MQTTnet 4.2.1.781

背景

MCU加4G模组要测试MQTT通讯,和功能开发,为方便自己调试,写了个小工具做简单命令首发

MQTT连接

MCU肯定是作为客户端client,项目中已经搭建好了MQTT Broker 服务器。

第一步需要先连接自己的服务器。

csharp 复制代码
//定义一个mqtt客户端句柄
public static IMqttClient _mqttClient = null;

private void MqttConnectAsync()
{
	//若已连接,则断开原来的连接,防止占用资源
	if (_mqttClient != null && _mqttClient.IsConnected == true)
	{
		_mqttClient.DisconnectAsync();
	}
	
	var optionsBuilder = new MqttClientOptionsBuilder()
	.WithTcpServer("mqtt-test.com", 1883) //服务器IP或域名 服务器端口号
	.WithCredentials("", "") //凭据 忽略
	.WithClientId("test_client") //客户端ID 如果写死则相同ID的同时客户端连接服务器时,会挤掉其他客户端 | 这里也跟可以生成随机数转成字符串
	.WithCleanSession() //清理会话
	.WithTls(new MqttClientOptionsBuilderTlsParameters
	{
		UseTls = false
	});

	var clientOptions = optionsBuilder.Build();
	_mqttClient = new MqttFactory().CreateMqttClient();//创建客户端

	//连接成功的回调函数
	_mqttClient.ConnectedAsync += _mqttClient_ConnectedAsync;
	
	//连接断开的回调函数
	_mqttClient.DisconnectedAsync += _mqttClient_DisconnectedAsync;
	
	//数据接收的回调函数
	_mqttClient.ApplicationMessageReceivedAsync += _mqttClient_ApplicationMessageReceivedAsync;

	//执行异步方式连接
	_mqttClient.ConnectAsync(clientOptions);
}

private Task _mqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
{
	//连接成功一般做2件事:一、告知上层已连接成功,二、订阅Topic来接收数据
	string topic2 = "/C2S/" + IMEI + "/UP";
    string topic3 = "/C2S/Public";
    _mqttClient.SubscribeAsync(topic3, MqttQualityOfServiceLevel.AtMostOnce);
    return Task.CompletedTask;
}

private Task _mqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
{
	//连接断开:告知上层连接已断开
    return Task.CompletedTask;
}

MQTT数据发送

csharp 复制代码
void _mqttClient_Publish(byte[] cmd)
{
    string topic = "S2C/" + IMEI + "/DOWN";
    //MQTT数据发送 即 publish 发布,需要2个参数:一、发布主题,二、发布数据(有效载荷)
    //发布主题,可以根据自己的规则定义,比如以设备4G模组的IMEI号组成
    _mqttClient.PublishBinaryAsync(topic, cmd);
}

MQTT数据接收

csharp 复制代码
private Task _mqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
{
    byte[] bytes = arg.ApplicationMessage.Payload;

    if (bytes[0] == 0x01
        && bytes[1] == 0x98
        && bytes[2] == 0x76)
    {
        byte[] byte_tmp = new byte[bytes.Length - 9];
        for (int i = 5; i < bytes.Length - 4; i++)
        {
            byte_tmp[i - 5] = bytes[i];
        }
        //数据定义中,上行数据添加固定头,其后跟字符串数据
        //每次接收时,判断固定头,提取后面的字符串数据进行打印
        textBox1.AppendText(System.Text.Encoding.UTF8.GetString(byte_tmp) + "\r\n");
    }
    else
    {
        textBox1.AppendText("收到非法消息\r\n");
    }
    return Task.CompletedTask;
}
相关推荐
.房东的猫11 小时前
ERP(金蝶云星空)开发【安装篇】
c#
fie888919 小时前
基于C#的推箱子小游戏实现
开发语言·c#
.房东的猫19 小时前
ERP(金蝶云星空)开发【业务数据中心创建和注册】
c#
bugcome_com20 小时前
C# 进阶核心知识点汇总|多项目开发 + 委托 + Lambda + 事件一次吃透
c#
SunflowerCoder1 天前
基于插件化 + Scriban 模板引擎的高效 HTTP 协议中心设计
http·c#
青云计划1 天前
知光项目用户关系模块
c#·linq
m5655bj1 天前
使用 C# 修改 PDF 页面尺寸
java·pdf·c#
专注VB编程开发20年1 天前
c#模仿内置 Socket.Receive(无需 out/ref,直接写回数据)
开发语言·c#
bugcome_com1 天前
【零基础入门】C# 核心教程:从 HelloWorld 到入门精髓
c#
JQLvopkk1 天前
C# 实现Http Json格式 Post 、Get 方法请求 winform服务器
http·c#·json