You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#使用MQTTnet连接MQTT broker总断开并抛出未处理异常如何解决

MQTT连接失败问题修复方案

根因定位

你使用的HiveMQ Cloud 8883端口为TLS加密传输端口,现有代码未启用TLS配置,无法通过服务端安全校验,是连接直接断开的核心原因。同时代码中大量使用Wait()做同步阻塞调用,容易引发线程死锁,且断开回调未打印异常信息,无法定位具体错误。

修复点

  • 新增TLS配置,适配HiveMQ Cloud的安全连接要求
  • 替换所有Wait()阻塞调用为异步等待,避免线程死锁
  • 断开回调中新增异常打印,方便问题定位
  • 调整Main方法为异步签名,符合异步编程规范

修正后完整代码

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

namespace TreonConsole
{
    class Program
    {
        private static IMqttClient _Client;
        private static IMqttClientOptions _options;
        static async Task Main(string[] args)
        {
            try
            {
                Console.WriteLine("Starting Subscriber...");

                //Create subscriber client
                var factory = new MqttFactory();
                _Client = factory.CreateMqttClient();
                string clientid = Guid.NewGuid().ToString();

                //Configure options, 新增WithTls启用TLS加密适配8883端口
                _options = new MqttClientOptionsBuilder()
                    .WithClientId(clientid)
                    .WithTcpServer("b925270106984f21be3ae9d1d48b400fh.s112.eu.hivemq.cloud", 8883)
                    .WithCredentials("iap", "Iap321?")
                    .WithCleanSession()
                    .WithTls() // 核心新增配置,启用TLS加密
                    .Build();

                //Handlers
                _Client.UseConnectedHandler(async e =>
                {
                    Console.WriteLine("Connected successfully with MQTT Brokers.");
                    //Subscribe to topic
                    await _Client.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("test").Build());
                });

                _Client.UseDisconnectedHandler(e =>
                {
                    Console.WriteLine("Disconnected from MQTT Brokers.");
                    // 打印断开异常,方便定位问题
                    if (e.Exception != null)
                    {
                        Console.WriteLine($"Disconnect reason: {e.Exception.Message}");
                    }
                });
                _Client.UseApplicationMessageReceivedHandler(e =>
                {
                    Console.WriteLine("Received Application Messages");
                    Console.WriteLine($"+Topic={e.ApplicationMessage.Topic}");
                    Console.WriteLine($"+Payload={Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                    Console.WriteLine($"+Qos={e.ApplicationMessage.QualityOfServiceLevel}");
                    Console.WriteLine($"Retain={e.ApplicationMessage.Retain}");
                    Console.WriteLine();
                });

                // 异步等待连接,不要用Wait()
                await _Client.ConnectAsync(_options);
                Console.WriteLine("Press Key to Exit");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
    }
}

验证注意事项

  • 确认MQTT broker地址、用户名、密码配置正确
  • 确认本地网络无防火墙拦截对目标节点8883端口的访问
  • 若仍连接失败,可将断开回调中打印的异常信息提供用于进一步定位

内容的提问来源于stack exchange,提问作者kamlesh jha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 08:42:04