这是我的代码:
public void connect(Context application) throws MqttException {
Log.d(MainActivity.TAG, "Connecting to MQTT");
String mqttServerUri = "tcp://18.219.333.193:1883";
String userName = "xxxxxxx";
String password = "xxxxxxx";
MqttAndroidClient client = new MqttAndroidClient(application, mqttServerUri, "mqtt-test");
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(false);
options.setAutomaticReconnect(true);
options.setKeepAliveInterval(60 * 10);
options.setMaxInflight(3000);
options.setUserName(userName);
options.setPassword(password.toCharArray());
client.connect(options, iMqttActionListener);
}
这是回调:
final IMqttActionListener iMqttActionListener = new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
MqttHandler.isConnected.set(true);
Log.d(TAG, "[MH] connected to mqtt server");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
MqttHandler.isConnected.set(false);
Log.e(TAG, "[MH] cannot connect to mqtt server", exception);
}
};
但是在执行连接方法时,我得到这个异常:
[MH] cannot connect to mqtt server
Bad user name or password (4)
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:28)
at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:988)
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:145)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:154)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:269)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
这与用户名或传递实际上错误时引发的异常相同。
但是当我替换这一行时:
client.connect(options, iMqttActionListener);
有了这个:
client.connect(options);
它工作正常,但我不知道它何时完成连接,所以它绝对不是用户/通行证问题。但我确实需要回调。
我该如何解决这个问题?
附注:我正在使用org.eclipse.paho.client.mqttv3
版本:1.2.0
<</p>
这不是错误,只是 API 设计中的一个缺陷。
如果你检查: org.eclipse.paho.android.service.MqttAndroidClient#connect(java.lang.Object, org.eclipse.paho.client.mqttv3.IMqttActionListener(
@Override
public IMqttToken connect(Object userContext, IMqttActionListener callback)
throws MqttException {
return connect(new MqttConnectOptions(), userContext, callback);
}
第一个参数不是连接选项,而是用户上下文。
因此,包括回调在内,正确的调用将是:
client.connect(options, null, iMqttActionListener);
这很简单。 Eclipse Paho Client
库有几个带回调的connect()
方法。
您可以在 MQTT 服务类示例中参考我的回答
我希望这对你有所帮助。