MQTT也可以理解成是一种消息队列。但是区别其它的消息队列,MQTT主要是针对低带宽高延迟的环境设计的,所以比较适合一些物联网的设备使用。相对来说也会比较轻量一点。MQTT也针对物联网领域的安全方便做了一些设计。
EMQX
在EMQX(https://cloud.emqx.com/console/)注册了一个免费的服务。
官方C#语言推荐用M2Mqtt来连接服务器。
用M2Mqtt来连接免费的测试服务器,能够正常成功。
示例教程:
https://docs.emqx.com/zh/cloud/latest/connect_to_deployments/c_sharp_sdk.html
但是用M2Mqtt来连接自己的服务端,一直连接不成功。
目前已经调研成功,主要是修改一下一行代码:
MqttClient client = new MqttClient(broker, port, true, MqttSslProtocols.TLSv1_2, null, null);
M2Mqtt
安装:
Install-Package M2Mqtt
示例代码:
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
string broker = "a88b8b81.ala.cn-hangzhou.emqxsl.cn";
int port = 8883;
string topic = "Csharp/mqtt";
string clientId = Guid.NewGuid().ToString();
string username = "你的用户名";
string password = "你的密码";
MqttClient client = ConnectMQTT(broker, port, clientId, username, password);
Subscribe(client, topic);
Publish(client, topic);
static MqttClient ConnectMQTT(string broker, int port, string clientId, string username, string password)
{
MqttClient client = new MqttClient(broker, port, true, MqttSslProtocols.TLSv1_2, null, null);
client.Connect(clientId, username, password);
if (client.IsConnected)
{
Console.WriteLine("Connected to MQTT Broker");
}
else
{
Console.WriteLine("Failed to connect");
}
return client;
}
static void Publish(MqttClient client, string topic)
{
int msg_count = 0;
while (true)
{
System.Threading.Thread.Sleep(1 * 1000);
string msg = "messages: " + msg_count.ToString();
client.Publish(topic, System.Text.Encoding.UTF8.GetBytes(msg));
Console.WriteLine("Send `{0}` to topic `{1}`", msg, topic);
msg_count++;
}
}
static void Subscribe(MqttClient client, string topic)
{
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
client.Subscribe(new string[] { topic }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
}
static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
string payload = System.Text.Encoding.Default.GetString(e.Message);
Console.WriteLine("Received `{0}` from `{1}` topic", payload, e.Topic.ToString());
}
标签:MqttClient,string,topic,M2Mqtt,MQTT,client,关于,调研
From: https://www.cnblogs.com/wzwyc/p/18496045