【问题标题】:gomobile build, the Paho mqtt client cannot connect to mqtt broker in APKgomobile build,Paho mqtt 客户端无法连接到 APK 中的 mqtt 代理
【发布时间】:2021-07-07 20:01:21
【问题描述】:

我正在做一个项目,我需要使用 gomobile tool 创建一个 Android 应用程序。 我在 Go 中的示例代码如下

    var broker = "127.0.0.1"
    //var broker = "broker.mqttdashboard.com"
    var port = 1883
    opts := mqtt.NewClientOptions()
    opts.AddBroker(fmt.Sprintf("tcp://%s:%d", broker, port))
    opts.SetClientID("go_mqtt_client")
    opts.SetConnectionLostHandler(connectLostHandler) // define what to do when connection is lost
    client := mqtt.NewClient(opts)
    tokenClient := client.Connect()
    if tokenClient.Wait() && tokenClient.Error() != nil {
        panic(tokenClient.Error())
    }
    ...

当我使用 “gomobile bind” 绑定此代码时,生成 Golang 插件并在 android 项目中调用它们没有问题。 Connections 满意,我可以验证本地 mqtt 代理 (mosquitto) 和 mqtt 客户端应用程序也在通信。

但是当我使用 "gomobile build -target=android" 生成 APK 文件时,连接函数会生成并出错。 为了能够测试日志,我使用了公共代理而不是本地 mqtt 代理。我换了

var 经纪人 = "127.0.0.1"

通过 HiveMQ 公共代理地址(我已经验证了公共代理功能)

var broker = "broker.mqttdashboard.com"

从 mqtt 客户端应用程序连接到 mqtt 代理似乎存在问题。这是我在日志中找到的确切错误消息:

E/Go:恐慌:网络错误:拨号 tcp:查找 broker.mqttdashboard.com:没有与主机名关联的地址 goroutine 11 [运行]:E / GoLog:恐慌:网络错误:拨号tcp:查找broker.mqttdashboard.com:没有与主机名关联的地址 E/Go:main.starting()

这是由我的代码中的 "panic(tokenClient.Error())" 部分生成的。

知道为什么连接没有使用“gomobile build”解决,而当我使用“gomobile bind”时它正在工作?

【问题讨论】:

  • 此错误将由call to net.DialTimeout within the library 生成。尝试直接与net.DialTimeout("tcp", "broker.mqttdashboard.com", time.Minute) 连接(我希望它会因同样的错误而失败)。我怀疑这可能是权限错误(参见 cmets re AndroidManifest.xml here)。
  • @Brits 感谢您的评论。你在右边,实际上是许可。几个小时前,我刚刚通过在我的 go 项目中添加 AndoridManifest.xml 文件并添加权限来修复它。当我意识到需要什么许可时,我会回复我的帖子。太神奇了,我也从同一个 example 得到了这个想法

标签: apk mqtt paho gomobile gomobile-android


【解决方案1】:

这是我可以解决问题的方法。

  1. 我将 AndoridManifest.xml 文件添加到主 go 包所在的同一目录中。

  2. 在清单标签()之间添加了以下行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-27
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    相关资源
    最近更新 更多