大家好,欢迎来到IT知识分享网。
m2mqtt库:https://github.com/eclipse/paho.mqtt.m2mqtt
m2mqtt手册:https://m2mqtt.wordpress.com/using-mqttclient/
m2mqtt下载:https://www.nuget.org/packages/M2Mqtt/
准备
- 本客户端使用VS2015进行开发,所以需要实现安装VS2015。
- 开发之前需要下载M2MQTT库。m2mqtt库的获取,可以使用vs的nuget来获取。
- 如果VS2015没有NuGet包管理器,可以按照https://jingyan.baidu.com/article/066074d636fd19c3c21cb0a2.html安装。
- 重启VS2015后,打开自己的C#工程,然后打开“工具”-“Nuget包管理器”-“程序包管理器控制台”
在控制台中输入“Install-Package M2Mqtt -Version 4.3.0”即可自动完成配置。
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
using System.Net.Security;
namespace m2mqtt_test
{
class Program
{
static void messageReceive(object sender, MqttMsgPublishEventArgs e)
{
string msg = "Topic:" + e.Topic + " Message:" + System.Text.Encoding.Default.GetString(e.Message);
Console.WriteLine(msg);
}
static bool cafileValidCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
string msg = "X509 链状态:";
foreach (X509ChainStatus status in chain.ChainStatus)
{
msg += status.StatusInformation + "\n";
}
msg += "SSL策略问题:" + (int)sslPolicyErrors;
Console.WriteLine(msg);
if (sslPolicyErrors != SslPolicyErrors.None)
return false;
return true;
}
static void Main(string[] args)
{
string brokerHostName = "192.168.1.38";
int brokerPort = 8883;
string clientId = "m2mqtt";
string username = "develop";
string password = "666666";
string[] topic = {"topic"};
byte[] qosLevels = { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE};
string caPath = "C:/MqttSSL/ca.crt";
X509Certificate caCert = new X509Certificate(caPath);
Console.WriteLine(caCert.ToString(true)+"\n"+caCert.ToString());
Console.ReadKey();
Console.WriteLine("------------------------分割线-------------------------------");
//无SSL连接
//MqttClient client = new MqttClient(brokerHostName,brokerPort,false,null,null,MqttSslProtocols.None);
try {
//单向SSL通信
MqttClient client = new MqttClient(brokerHostName, brokerPort, true, caCert, null, MqttSslProtocols.TLSv1_2, new RemoteCertificateValidationCallback(cafileValidCallback));
//消息接受
client.MqttMsgPublishReceived += new MqttClient.MqttMsgPublishEventHandler(messageReceive);
//连接Broker
client.Connect(clientId, username, password);
client.Subscribe(topic, qosLevels);
}
catch (System.Exception)
{
Console.WriteLine("连接失败!");
Console.ReadKey();
}
}
}
}
- 本客户端连接Broker是mosquitto,可以到本人的博客找到:http://blog.csdn.net/sxpsxp12/article/details/77870109
- 可能C#遇到的问题:一个是因为客户端和服务端以及签发机构的证书信息相同,导致客户端和服务端不能识别证书,导致连接失败。另外一个原因是因为自己生成的证书没有添加到系统的根证书中,不被根证书所信任导致连接失败。
欢迎各位大佬右侧点赞、关注、打赏,我们再会。。。
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/12897.html