一、服務端
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();