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.

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

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码