dstt1818 2016-10-15 08:19
浏览 100
已采纳

MQTT现有客户

I am using eclipse paho golang library to create new MQTT client for a particular client id:

func CreateMQTTClient(clientID string) (client MQTT.Client) {
    username := viper.GetString("messaging.rabbitmq.username")
    password := viper.GetString("messaging.rabbitmq.password")
    host := viper.GetString("messaging.rabbitmq.host")
    mqqtPort := viper.GetString("messaging.rabbitmq.mqqtPort")
    rabbitMqMQQTURL := "tcp://" + host + ":" + mqqtPort
    opts := MQTT.NewClientOptions().AddBroker(rabbitMqMQQTURL)
    opts.SetClientID(clientID)
    opts.Username = username
    opts.Password = password
    opts.SetCleanSession(false)
    cli := MQTT.NewClient(opts)

    if (!cli.IsConnected()) {
        log.Println("I came here for cli:", clientID)
        if token := cli.Connect(); token.Wait() && token.Error() != nil {
            log.Print(token.Error())
        }
    }

    return cli

}

I am not sure how do I get this client back using clientId. If I call CreateMQTTClient again, all existing subscriptions are lost.

  • 写回答

1条回答 默认 最新

  • dox90448 2016-10-18 08:14
    关注

    There is, unfortunately, no way to query an MQTT server to find out what subscriptions it has active for your client id. When you connect with the same client ID as a previous session the server assumes you have the same state as last time you were connected, but there is no way to pre connect a MessageHandler with a topic in the Go client, the only way to add and remove them is with Subscribe/Unsubscribe.

    Assuming the server is working correctly, if you connect as above reusing a client id the server will continue to send you messages according to your previous subscriptions but the Go client doesn't know what to do with them so will invoke the default message handler. The best way to currently resolve this would be to call Subscribe() in the OnConnectHandler, assuming the topics you want to subscribe to are predetermined rather than dynamic.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?