c# mqtt 服务端、客户端简易例子
我用的是HslCommunication(在vs的nuget上下在的,直接搜这个dll名字就行了),本来想用mqttnet的,发现新版本是3.多了,网上的教程都是2.7多了,我项目又比较急,我也懒得研究了,找到了一篇HslCommunication的用法,我整理了下。下面上代码
服务端:
using HslCommunication; using HslCommunication.MQTT; using System; using System.Globalization; using System.Net.Http.Headers; using System.Text; namespace MqttTestServer { class Program { static void Main(string[] args) { MyClass my = new MyClass(); my.Start(); Console.ReadLine(); } } public class MyClass { private MqttServer mqttServer = null; public void Start() { mqttServer = new MqttServer(); mqttServer.ServerStart(6666); mqttServer.ClientVerification += OnConnect; mqttServer.OnClientDisConnected += OnClientOffline; mqttServer.OnClientConnected += OnClientOnline; mqttServer.OnClientApplicationMessageReceive += OnClientReceive; } /// <summary> /// 客户端信息的字符串 /// </summary> /// <param name="session"></param> /// <returns></returns> private string ClientInfoString(MqttSession session) { return string.Format("ID:{0}, 用户名:{1} ,Ip:{2}", session.ClientId, session.UserName, session.EndPoint); } /// <summary> /// 客户端下线时候会触发这个回调 /// </summary> /// <param name="session"></param> private void OnClientOffline(MqttSession session) { Console.WriteLine("客户端下线了!" + ClientInfoString(session)); } /// <summary> /// 客户端上线的时候会触发这个回调 /// </summary> /// <param name="session"></param> private void OnClientOnline(MqttSession session) { Console.WriteLine("客户端上线了!" + ClientInfoString(session)); } /// <summary> /// 当有客户端连接上来时会触发这个回调,返回0是通过,否则就是登录失败 /// </summary> /// <param name="clientId"></param> /// <param name="userName"></param> /// <param name="passwrod"></param> /// <returns></returns> private int OnConnect(string clientId, string userName, string passwrod) { Console.WriteLine("客户端连接了。"); return 0; } /// <summary> /// 客户端收到消息时触发 /// </summary> /// <param name="session"></param> /// <param name="message"></param> private void OnClientReceive(MqttSession session, MqttClientApplicationMessage message) { Console.WriteLine("客户端:" + ClientInfoString(session) + "收到消息了:" + Encoding.UTF8.GetString(message.Payload)); } } }
客户端:
using System; using System.Text; using System.Threading; using HslCommunication; using HslCommunication.MQTT; namespace MqttTestClient { class Program { static void Main(string[] args) { MyClass mc = new MyClass(); mc.Start(); mc.Connect();//连接 mc.Regist();//注册 Console.WriteLine("输入“send”发送消息"); string s = Console.ReadLine(); if (s == "send") { Console.WriteLine("我发送成功了"); mc.SendMsg(); } Console.ReadLine(); } public class MyClass { private MqttClient mqttClient = null; public void Start() { mqttClient = new MqttClient(new MqttConnectionOptions() { ClientId = "ABC", IpAddress = "127.0.0.1", Port = 6666, Credentials = new MqttCredential("admin", "admin"), // 设置了用户名和密码 }); } public void Connect() { // 连接 OperateResult connect = mqttClient.ConnectServer(); if (connect.IsSuccess) { Console.WriteLine("Success"); } else { Console.WriteLine("Failed"); } } public void SendMsg() { // 测试发布 mqttClient.PublishMessage(new MqttApplicationMessage() { Topic = "A", // 主题 QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, // 消息等级 Payload = Encoding.UTF8.GetBytes("This is test message!"), // 数据 Retain = false, // 是否保留 }); } public void Regist() { // 订阅测试,在label1上显示结果 mqttClient.OnMqttMessageReceived += MqttClient_OnMqttMessageReceived; // 调用一次即可 mqttClient.SubscribeMessage("A"); // 订阅A的主题 } private void MqttClient_OnMqttMessageReceived(string topic, byte[] payload) {
//topic是主题名字。payload是消息内容; Console.WriteLine("我收到了消息了"); string s = Encoding.UTF8.GetString(payload); Console.WriteLine(s); } } } }
运行结果: