This topic provides answers to some commonly asked questions about connecting the ApsaraMQ for MQTT broker to the client.

Why is the connection failed error returned when I use an Android demo?

Problem description

  • The resources are correctly configured, and the network can be accessed.
  • The AccessKey ID and AccessKey secret are authorized and correctly entered.

Possible cause

The format of the endpoint is incorrect. Specify the endpoint in one of the following formats: tcp://Endpoint:1883 or tls://Endpoint:8883.

Why does the client immediately disconnects after the consumer subscribes?

Possible cause: The setting and naming format of the topics are incorrect. Check the settings of your parent topic and subtopic.
Parent topic
MQTT is a messaging protocol that is based on the publish-subscribe model. In MQTT, each message belongs to a topic. The MQTT protocol supports multiple levels of topics. A level-1 topic is a parent topic. Before you use ApsaraMQ for MQTT, you must create a parent topic in the ApsaraMQ for MQTT console or the ApsaraMQ for RocketMQ console.
Subtopic
A level-2 topic or level-3 topic is a subtopic of a parent topic in Message Queue for MQTT. You can specify subtopics in your application code without the need to create subtopics in the Message Queue for MQTT console. You can specify the subtopics in the following format: <Name of the parent topic>/<Name of the level-2 topic>/<Name of the level-3 topic>. The parent topic and the subtopics are separated with forward slashes (/). Example: SendMessage/demo/producer. The total length of the names for a parent topic and the subtopics cannot exceed 64 characters in ApsaraMQ for MQTT. If the preceding condition is not met, a client exception occurs.

Why is the number of subscriptions that are displayed in the console higher than the number of subscriptions that are used in actual scenarios?

If the cleanSession parameter is set to false, the subscriptions are not cleared even after the client is disconnected.

If you do not want to retain subscriptions after the client is disconnected, you can use the subscription cleanup feature to clear the subscriptions. For more information, see Clear subscription for a topic.

Why did the client repeatedly reconnect and return the "invalid param" error?

Possible cause: The broker denied the connection request because the size of the message body exceeded the limit. In ApsaraMQ for MQTT, the size of a message body cannot exceed 64 KB.

Why did the client unexpectedly disconnect from the broker when no modifications are performed on the business side?

Possible causes:

  • The device is shut down or the network cannot be accessed.
  • If you use token-based authentication, the client disconnects from the broker after the token expires and the connection retry also fails if no new token is obtained.

How do I specify the heartbeat timeout period of the client?

Call the MqttConnectOptions class.

Sample code:
String clientId = mqttTools.getClientId();
mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setUserName("Signature|" + accessKey + "|" + instanceId);
mqttConnectOptions.setPassword(mqttTools.macSignature(clientId).toCharArray());
mqttConnectOptions.setCleanSession(true);
// The heartbeat timeout period of the client. Default value: 90 seconds. 
mqttConnectOptions.setKeepAliveInterval(90);
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setMqttVersion(MQTT_VERSION_3_1_1);
mqttConnectOptions.setConnectionTimeout(5000);
mqttLogger.info("MQTT is connect setting={},clientId={}", JSON.toJSONString(mqttConnectOptions), clientId);
mqttClient = new MqttClient("tcp://" + endPoint + ":1883", clientId, memoryPersistence);
mqttClient.setTimeToWait(5000);
mqttClient.setCallback(this.getMqttCallbackExtended());
mqttClient.connect(mqttConnectOptions);

Why did the "valid owner failed" error occur when the client is connected to the broker?

Check the following items:
  • Is the instance name correctly specified?
  • Did you create the consumer group and the topic in the console and correctly specify their names?
  • Did you correctly specify the information about the group or topic in the specified instance?

Why did the "connection reset by peer" error occur?

Account conflict occurs if the client ID exists. In this case, the broker disconnects from the client and the client continues to send data over the TCP connection that is established. This triggers the broker socket to send reset (RST) packets.

Make sure that the client ID that you specify is globally unique. For more information, see Limits on clients.

How do I configure the automatic connection feature for the SDK for Java client in Message Queue for MQTT?

Enable the automatic client reconnection feature for the SDK for Java client

mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);

After you set the autoReconnect parameter to true, the SDK for Java client in ApsaraMQ for MQTT is automatically reconnected.

mqttClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
                /**
                 * The topic that you must subscribe to after the client connection is established. 
                 */
                System.out.println("connect success");
            }

            @Override
            public void connectionLost(Throwable throwable) {
                throwable.printStackTrace();
            }

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                /**
                 * The callback that is called to consume the messages that are sent. Make sure that the callback does not throw exceptions. If a response is returned for the callback, the messages are consumed. 
                 * The messages must be consumed in a specified period. If a message is not consumed in the timeout period that you specified for the Message Queue for MQTT broker, the Message Queue for MQTT broker may attempt to resend the message in reliable transmission mode. Make sure that the business data is idempotent. 
                 * For information about the timeout period, see Limits. 
                 */
                System.out.println(
                    "receive msg from topic " + s + " , body is " + new String(mqttMessage.getPayload()));

            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                System.out.println("send msg succeed topic is : " + iMqttDeliveryToken.getTopics()[0]);
            }
});

When the connectComplete method in the callback of the client is called, the connection or reconnection is successful, and no attention on the connection status is required from users. In this case, the re-established connection is no longer the previous one. As a result, actions that are performed on the previous connection, such as sending or subscribing to messages, do not take effect on the new connection.

You must subscribe to a new topic. This way, users can continue sending and subscribing to messages.

@Override
public void connectComplete(boolean reconnect, String serverURI) {
    /**
    * The topic that you must subscribe to after the client connection is established. 
    */
    System.out.println("connect success");
    executorService.submit(new Runnable() {
        @Override
        public void run() {
            try {
                final String topicFilter[] = {mq4IotTopic};
                final int[] qos = {qosLevel};
                mqttClient.subscribe(topicFilter, qos);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    });
}

Manual maintenance of a client connection from users

mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(false);

If the autoReconnect parameter is set to false, the ApsaraMQ for MQTT client does not automatically reconnect after it is disconnected.

When the Message Queue for MQTT client is disconnected, exceptions are captured by users. In this case, users must manually terminate the original connection and establish a new connection.