#进入bin文件,执行命令apollo.cmd create [文件夹名称]#进入新建文件夹下bin文件夹,在执行命令apollo-broker.cmd run
客户端代码实现
nuget 安装包
MQTTnet
代码实现
发布
Console.WriteLine("---------------MQTT客户端 通信开始------------");//建立连接var conn = new MqttFactory().CreateManagedMqttClient();IMqttClientOptions value = new MqttClientOptionsBuilder().WithClientId("MQTTClie").WithTcpServer("127.0.0.1",1883).WithCredentials("admin","123456").Build(); IManagedMqttClientOptions options = new ManagedMqttClientOptionsBuilder().WithClientOptions(value).Build(); await conn.StartAsync(options); //客户端发布 MqttApplicationMessage mqttApplicationMessage = new MqttApplicationMessageBuilder().WithTopic("server").WithPayload(Encoding.UTF8.GetBytes("Good Luck!")).Build();await conn.PublishAsync(mqttApplicationMessage);Console.WriteLine("---------------MQTT客户端 通信结束------------");Console.ReadLine();
订阅
Console.WriteLine("---------------MQTT客户端 通信开始------------");//建立连接var conn = new MqttFactory().CreateManagedMqttClient();IMqttClientOptions value = new MqttClientOptionsBuilder().WithClientId("MQTTClie").WithTcpServer("127.0.0.1",1883).WithCredentials("admin","123456").Build(); //响应订阅主题conn.ApplicationMessageReceivedHandler= new MqttApplicationMessageReceivedHandlerDelegate(e => {Console.WriteLine($"收到消息{e.ApplicationMessage.ConvertPayloadToString()},来自clientID{e.ClientId}");});IManagedMqttClientOptions options = new ManagedMqttClientOptionsBuilder().WithClientOptions(value).Build(); await conn.StartAsync(options);//订阅主题过滤器 MqttTopicFilter topicFilter = new MqttTopicFilterBuilder()//设置主题.WithTopic("server")//设置服务质量.WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce).Build(); await conn.SubscribeAsync(topicFilter); Console.WriteLine("---------------MQTT客户端 通信结束------------");Console.ReadLine();
既是发布也是订阅
Console.WriteLine("---------------MQTT客户端 通信开始------------");//建立连接var conn = new MqttFactory().CreateManagedMqttClient();//响应订阅主题conn.ApplicationMessageReceivedHandler= new MqttApplicationMessageReceivedHandlerDelegate(e => {Console.WriteLine($"收到消息{e.ApplicationMessage.ConvertPayloadToString()},来自clientID{e.ClientId}");});await Task.Delay(1000);IMqttClientOptions value = new MqttClientOptionsBuilder().WithClientId("MQTTClie").WithTcpServer("127.0.0.1",1883).WithCredentials("admin","123456").Build(); IManagedMqttClientOptions options = new ManagedMqttClientOptionsBuilder().WithClientOptions(value).Build(); await conn.StartAsync(options);//订阅主题MqttTopicFilter topicFilter = new MqttTopicFilterBuilder()//设置主题.WithTopic("server")//设置服务质量.WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce).Build();await conn.SubscribeAsync(topicFilter);//客户端发布 MqttApplicationMessage mqttApplicationMessage = new MqttApplicationMessageBuilder().WithTopic("server").WithPayload(Encoding.UTF8.GetBytes("Good Luck!")).WithRetainFlag (true) .Build();await conn.PublishAsync(mqttApplicationMessage);Console.WriteLine("---------------MQTT客户端 通信结束------------");Console.ReadLine();