工业互联-基于C#的MQTT客户端开发
客户端对象创建:
1 IManagedMqttClient client = new MqttFactory().CreateManagedMqttClient(); // 连接到mqtt服务器 2 IMqttClientOptions clientOptions = new MqttClientOptionsBuilder() 3 .WithClientId("XFEX1") 4 .WithTcpServer("127.0.0.1", 1121) 5 .WithCredentials("admin", "123456") 6 .Build(); // 客户端ip\端口\用户名\密码信息 7 IManagedMqttClientOptions options = new ManagedMqttClientOptionsBuilder() 8 .WithClientOptions(clientOptions) 9 .Build(); // 生成配置对象
客户端的订阅与发布:
(1)订阅topic过滤器:
1 MqttTopicFilter topicFilter = new MqttTopicFilterBuilder() 2 .WithTopic("test") // topic名称 3 .WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce) 4 .Build(); 5 await client.SubscribeAsync(topicFilter);
(2)发布消息
1 // 针对topic发布消息 2 string msg = "Hello,MU9191"; 3 MqttApplicationMessage message = new MqttApplicationMessageBuilder() 4 .WithTopic("test") // topic名称 5 .WithPayload(Encoding.Default.GetBytes(msg)) 6 .WithRetainFlag(false) 7 .Build(); 8 await client.PublishAsync(message);
客户端接收消息:
1 client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(Client_ApplicationMessageReceived);
1 /// <summary> 2 /// 响应订阅topic的消息 3 /// </summary> 4 /// <param name="e"></param> 5 public static void Client_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e) 6 { 7 Console.WriteLine(">>> 收到消息:" + e.ApplicationMessage.ConvertPayloadToString() + 8 ",来自客户端" + e.ClientId + ",topic:" + e.ApplicationMessage.Topic); 9 }
客户端连接状态:
1 // 客户端连接状态 2 client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(e => { 3 Console.WriteLine($"客户端连接状态:{e.ConnectResult.ResultCode}"); 4 });