这是我的代码:
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);
}
};
但是在执行connect方法时,出现此异常:
[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);
它工作正常,但我不知道它何时完成连接,因此它绝对不是用户/通过问题。但是我确实需要回调。
我该如何解决?
PS:
我正在使用org.eclipse.paho.client.mqttv3
版本:1.2.0
答案 0 :(得分:1)
这不是错误,只是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);
答案 1 :(得分:-1)