c# 批量mqtt_MQTT通讯(基于C# MQTTNet开发)

本文介绍了如何使用C#的MQTTNet库建立MQTT客户端,连接到服务器并进行消息的订阅与发布。通过示例代码展示了连接、订阅、发布消息以及处理服务器连接状态变化的方法。
摘要由CSDN通过智能技术生成

【实例简介】

基于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);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值