一、服务端
1.添加引用MQTTnet类库
2.代码:启动一个MQTT服务
1 // 启动一个MQTT服务器 2 // MQTT 3 IMqttServer server = new MqttFactory().CreateMqttServer(); 4 server.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(new Action<MqttServerClientConnectedEventArgs>(Connected)); 5 6 // IP Port 用户名 密码 7 MqttServerOptionsBuilder builder = new MqttServerOptionsBuilder() 8 .WithDefaultEndpointBoundIPAddress(System.Net.IPAddress.Parse("127.0.0.1"))// 指定IP 9 .WithDefaultEndpointPort(1883)// 默认使用1883端口,换成其他端口可能通信不了 10 .WithConnectionValidator(valid => 11 { 12 // 用户名和密码验证 13 if (valid.Username != "admin" && valid.Password != "123456") 14 { 15 valid.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword; 16 } 17 else 18 valid.ReturnCode = MqttConnectReturnCode.ConnectionAccepted; 19 }); 20 IMqttServerOptions options = builder.Build(); 21 // 启动 22 await server.StartAsync(options); 23 24 Console.WriteLine("MQTT服务已启动......"); 25 26 // 1、知道有哪个连接进来了 27 // 2、订阅-主题 发布-主题(负载 内容) 28 // 3、服务端接收到一个消息的时候,中转出去(发布的过程:主题进行发布:多个客户端)
二、客户端
1.添加包“MQTTnet.Extensions.ManagedClient”的引用
2.代码:启动一个MQTT的客户端
1 // 启动一个MQTT的客户端 2 IManagedMqttClient mqttClient = new MqttFactory().CreateManagedMqttClient(); 3 // 客户端ID IP Port 用户名 密码 4 5 var clientOptions = new MqttClientOptionsBuilder() 6 .WithClientId(Guid.NewGuid().ToString()) 7 .WithTcpServer("127.0.0.1", 1883) 8 .WithCredentials("admin", "123456"); 9 var option = new ManagedMqttClientOptionsBuilder() 10 .WithClientOptions(clientOptions.Build()); 11 mqttClient.StartAsync(option.Build()).GetAwaiter().GetResult(); 12 13 // 订阅一个主题 14 mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("Test").Build()); 15 mqttClient.UseApplicationMessageReceivedHandler(msg => 16 { 17 Debug.WriteLine(Encoding.UTF8.GetString(msg.ApplicationMessage.Payload)); 18 }); 19 20 // 各设备订阅的主题 数据库里维护 21 22 MqttApplicationMessage msg = new MqttApplicationMessage(); 23 msg.Topic = "测试发布"; 24 msg.Payload = Encoding.UTF8.GetBytes("客户端发布消息"); 25 msg.QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce; 26 mqttClient.PublishAsync(msg).GetAwaiter().GetResult();
标签:mqttClient,C#,报文,MQTT,valid,msg,new,客户端 From: https://www.cnblogs.com/jiangyuhu/p/18276778