android - Paho Mqtt Android 客户端错误 : Invalid client handle, 非法参数异常(应用程序运行时随时随机出现)

标签 android mqtt paho

Paho Mqtt Android 客户端错误:无效的客户端句柄、非法参数异常(应用程序运行时随时随机出现)

使用PahoAndroidMqtt客户端库 连接代码:

@Override
    public IMqttToken connect(MqttConnectOptions options, Object userContext,
            IMqttActionListener callback) throws MqttException {

        IMqttToken token = new MqttTokenAndroid(this, userContext,
                callback);

        connectOptions = options;
        connectToken = token;

        /*
         * The actual connection depends on the service, which we start and bind
         * to here, but which we can't actually use until the serviceConnection
         * onServiceConnected() method has run (asynchronously), so the
         * connection itself takes place in the onServiceConnected() method
         */
        if (mqttService == null) { // First time - must bind to the service
            Intent serviceStartIntent = new Intent();
            serviceStartIntent.setClassName(myContext, SERVICE_NAME);
            Object service = myContext.startService(serviceStartIntent);
            if (service == null) {
                IMqttActionListener listener = token.getActionCallback();
                if (listener != null) {
                    listener.onFailure(token, new RuntimeException(
                            "cannot start service " + SERVICE_NAME));
                }
            }

            // We bind with BIND_SERVICE_FLAG (0), leaving us the manage the lifecycle
            // until the last time it is stopped by a call to stopService()
            myContext.bindService(serviceStartIntent, serviceConnection,
                    Context.BIND_AUTO_CREATE);

            if (!receiverRegistered) registerReceiver(this);
        }
        else {
            pool.execute(new Runnable() {

                @Override
                public void run() {
                    doConnect();

                    //Register receiver to show shoulder tap.
                    if (!receiverRegistered) registerReceiver(MqttAndroidClient.this);
                }

            });
        }

        return token;
    }

    private void registerReceiver(BroadcastReceiver receiver) {
        IntentFilter filter = new IntentFilter();
                filter.addAction(MqttServiceConstants.CALLBACK_TO_ACTIVITY);
                LocalBroadcastManager.getInstance(myContext).registerReceiver(receiver, filter);
                receiverRegistered = true;
    }

    /**
     * Actually do the mqtt connect operation
     */
    private void doConnect() {
        if (clientHandle == null) {
            clientHandle = mqttService.getClient(serverURI, clientId,myContext.getApplicationInfo().packageName,
                    persistence);
        }
        mqttService.setTraceEnabled(traceEnabled);
        mqttService.setTraceCallbackId(clientHandle);

        String activityToken = storeToken(connectToken);
        try {
            mqttService.connect(clientHandle, connectOptions, null,
                    activityToken);
        }
        catch (MqttException e) {
            IMqttActionListener listener = connectToken.getActionCallback();
            if (listener != null) {
                listener.onFailure(connectToken, e);
            }
        }
    }

抛出错误的 Mqtt 服务类代码是:

 /**
   * Get an MqttConnection object to represent a connection to a server
   *
   * @param serverURI specifies the protocol, host name and port to be used to connect to an MQTT server
   * @param clientId specifies the name by which this connection should be identified to the server
   * @param contextId specifies the app conext info to make a difference between apps
   * @param persistence specifies the persistence layer to be used with this client
   * @return a string to be used by the Activity as a "handle" for this
   *         MqttConnection
   */
  public String getClient(String serverURI, String clientId, String contextId, MqttClientPersistence persistence) {
    String clientHandle = serverURI + ":" + clientId+":"+contextId;
    if (!connections.containsKey(clientHandle)) {
      MqttConnection client = new MqttConnection(this, serverURI,
          clientId, persistence, clientHandle);
      connections.put(clientHandle, client);
    }
    return clientHandle;
  }

 /**
   * Get the MqttConnection identified by this client handle
   *
   * @param clientHandle identifies the MqttConnection
   * @return the MqttConnection identified by this handle
   */
  private MqttConnection getConnection(String clientHandle) {
    MqttConnection client = connections.get(clientHandle);
    if (client == null) {
      throw new IllegalArgumentException("Invalid ClientHandle");
    }
    return client;
  }

StackTrace 是:

  Fatal Exception: java.lang.IllegalArgumentException: Invalid ClientHandle
       at org.eclipse.paho.android.service.MqttService.getConnection(MqttService.java:588)
       at org.eclipse.paho.android.service.MqttService.connect(MqttService.java:328)
       at org.eclipse.paho.android.service.MqttAndroidClient.doConnect(MqttAndroidClient.java:467)
       at org.eclipse.paho.android.service.MqttAndroidClient.access$200(MqttAndroidClient.java:76)
       at org.eclipse.paho.android.service.MqttAndroidClient$1.run(MqttAndroidClient.java:435)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
       at java.lang.Thread.run(Thread.java:818)

最佳答案

我认为您的问题是您使用的客户端与颁发 IMqttToken 的客户端不同。

尝试通过执行以下操作来获取正确的客户引用:

Kotlin :

val currentClient = asyncActionToken!!.client          

Java:

IMqttAsyncClient currentClient = asyncActionToken.getClient()

关于android - Paho Mqtt Android 客户端错误 : Invalid client handle, 非法参数异常(应用程序运行时随时随机出现),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44408854/

相关文章:

python - MQTT 在 python 中通过 websocket

google-cloud-platform - 是否可以通过 Javascript 连接到 Google IOT Core MQTT Bridge?

android - 尝试在空对象引用上调用虚拟方法 'void android.nfc.tech.MifareClassic.connect()'

java - Android 开发者上的 CustomButton

azure iothub直接方法未按预期工作

javascript - 如何使用 MQTT JavaScript 创建 JSON?

Android Tracking App - 检查是否有人离特定点越来越近或越来越远

java - 连接到 Mysql 数据库 - JDBC 或 PHP

python - Mosquitto 的问题和遗嘱(遗嘱)

java - 在 Spring Boot 中添加具有不同客户端 ID 的 MQTT 连接