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

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.

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

报告相同问题?