You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

MQTTNet 4.1.6.1152版本出现命名空间错误求助

问题解决:MQTTNet 4.x命名空间错误

你遇到的错误是因为MQTTNet 4.x版本对命名空间做了重构,原来的MQTTnet.Client.OptionsMQTTnet.Client.Subscribing子命名空间已被移除,相关类型全部合并到MQTTnet.Client主命名空间下。

解决步骤:

  • 删除代码中这两行多余的using引用:
    using MQTTnet.Client.Options;
    using MQTTnet.Client.Subscribing;
    
  • 保留using MQTTnet.Client;即可,MqttClientOptionsBuilderMqttClientSubscribeOptionsBuilder等类型现在都属于这个命名空间。

修改后的完整代码:

using System;
using System.Text;
using System.Threading.Tasks;
using MQTTnet;
using MQTTnet.Client;

namespace OTtoIT
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string brokerAddress = "0.0.0.0";  // Your MQTT broker IP address
            int brokerPort = 1883;  // Default MQTT port
            string topic = "#";  // Your MQTT topic

            // Create a new MQTT client
            var mqttClient = new MqttFactory().CreateMqttClient();

            // Create client options using the MqttClientOptionsBuilder
            var mqttClientOptions = new MqttClientOptionsBuilder()
                .WithClientId("YourClientId")
                .WithTcpServer(brokerAddress, brokerPort)
                .WithCleanSession()
                .Build();

            // Set up the handler for receiving messages
            mqttClient.ApplicationMessageReceivedAsync += e =>
            {
                var payload = Encoding.UTF8.GetString(e.ApplicationMessage.PayloadSegment.ToArray());
                Console.WriteLine($"Received message: {payload}");
                return Task.CompletedTask;
            };

            // Connect to the MQTT broker
            await mqttClient.ConnectAsync(mqttClientOptions);
            Console.WriteLine("Connected to the broker.");

            // Subscribe to the topic
            var subscribeOptions = new MqttClientSubscribeOptionsBuilder()
                .WithTopicFilter(f => { f.WithTopic(topic); })
                .Build();

            await mqttClient.SubscribeAsync(subscribeOptions);
            Console.WriteLine($"Subscribed to topic: {topic}");

            // Keep the application running to receive messages
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();

            // Disconnect the client
            await mqttClient.DisconnectAsync();
            Console.WriteLine("Disconnected from the broker.");
        }
    }
}

额外说明:

MQTTNet从3.x升级到4.x时,除了命名空间调整,部分API有细微变化,但你代码里用到的核心Builder类用法基本兼容,删除多余引用后即可正常运行。

内容的提问来源于stack exchange,提问作者Arun kumar K

火山引擎 最新活动