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

Android/MAUI Blazor项目中MqttNet服务器无法被PC客户端连接

Android Blazor MAUI MQTT服务器无法被PC客户端连接的排查与解决

我创建了一个Android Blazor MAUI服务器项目,将其作为前台服务绑定并启动,但无法通过PC客户端连接到该服务器。测试其他Android MQTT Broker应用可正常连接,说明我的平板设备对外可访问。已尝试使用本地IP和设备IP进行连接,但均未成功。核心代码如下:

public async Task StartServer()
{
    IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];

    var result = new List<IPAddress>();
    try
    {
        var upAndNotLoopbackNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces()
            .Where(n => n.NetworkInterfaceType != NetworkInterfaceType.Loopback 
                && n.OperationalStatus == OperationalStatus.Up);

        foreach (var networkInterface in upAndNotLoopbackNetworkInterfaces)
        {
            var iPInterfaceProperties = networkInterface.GetIPProperties();

            var unicastIpAddressInformation = iPInterfaceProperties.UnicastAddresses
                .FirstOrDefault(u => u.Address.AddressFamily == AddressFamily.InterNetwork);

            if (unicastIpAddressInformation == null)
                continue;

            result.Add(unicastIpAddressInformation.Address);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Unable to find IP: {ex.Message}");
    }

    // if (result.Count() > 0)
    // {
    //     ipAddress = result.FirstOrDefault();
    // }

    Console.Write("IP ADRESS: ");
    Console.WriteLine(ipAddress);

    var options = new MqttServerOptionsBuilder()
        .WithDefaultEndpointPort(1883)
        .WithDefaultEndpointBoundIPAddress(ipAddress)
        .WithDefaultEndpointBoundIPV6Address(IPAddress.None)
        .WithPersistentSessions()
        .WithDefaultEndpointPort(1883)
        .WithKeepAlive()
        .WithoutEncryptedEndpoint()
        .Build();

    var server = new MqttFactory().CreateMqttServer(options);
    try
    {
        await server.StartAsync();
        Console.WriteLine("MQTT SERVER STARTED..............");

        await Task.CompletedTask;
        // await server.StopAsync();
        // Console.WriteLine("MQTT SERVER STOPPED..............");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

问题排查

  • IP绑定错误:代码中已实现局域网IP排查逻辑,但被注释,当前使用的Dns.GetHostEntry(Dns.GetHostName()).AddressList[0]大概率是回环地址(127.0.0.1)或无法被局域网PC访问的IP
  • 冗余配置:重复调用WithDefaultEndpointPort(1883),属于无效冗余代码
  • 权限缺失:Android应用可能缺少必要网络权限,导致服务器无法监听外部连接

解决方案

  1. 启用有效IP绑定:取消注释IP替换逻辑,使用排查到的局域网IP绑定服务器
  2. 添加必要权限:在Android项目的AndroidManifest.xml中添加网络及前台服务权限
  3. 验证网络环境:确保PC与Android设备处于同一局域网,使用Android设备的局域网IP(如192.168.x.x)连接
  4. 检查端口拦截:确认Android设备防火墙未拦截1883端口

修改后的核心代码

public async Task StartServer()
{
    IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];

    var result = new List<IPAddress>();
    try
    {
        var upAndNotLoopbackNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces()
            .Where(n => n.NetworkInterfaceType != NetworkInterfaceType.Loopback 
                && n.OperationalStatus == OperationalStatus.Up);

        foreach (var networkInterface in upAndNotLoopbackNetworkInterfaces)
        {
            var iPInterfaceProperties = networkInterface.GetIPProperties();

            var unicastIpAddressInformation = iPInterfaceProperties.UnicastAddresses
                .FirstOrDefault(u => u.Address.AddressFamily == AddressFamily.InterNetwork);

            if (unicastIpAddressInformation == null)
                continue;

            result.Add(unicastIpAddressInformation.Address);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Unable to find IP: {ex.Message}");
    }

    // 启用局域网IP绑定逻辑
    if (result.Count > 0)
    {
        ipAddress = result.FirstOrDefault();
    }

    Console.Write("IP ADRESS: ");
    Console.WriteLine(ipAddress);

    var options = new MqttServerOptionsBuilder()
        .WithDefaultEndpointPort(1883)
        .WithDefaultEndpointBoundIPAddress(ipAddress)
        .WithDefaultEndpointBoundIPV6Address(IPAddress.None)
        .WithPersistentSessions()
        .WithKeepAlive()
        .WithoutEncryptedEndpoint()
        .Build();

    var server = new MqttFactory().CreateMqttServer(options);
    try
    {
        await server.StartAsync();
        Console.WriteLine("MQTT SERVER STARTED..............");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

必要权限配置

在AndroidManifest.xml中添加以下权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

内容的提问来源于stack exchange,提问作者N. OZER SENOL

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 20:16:14