[
Date Prev][
Date Next][
Thread Prev][
Thread Next][
Date Index][
Thread Index]
[
List Home]
Hello,
I use paho MQTT library in my application, sometimes, I need to close connection with broker, and then shut down MQTT client completely, then connect to another, to accomplish that I run disconnect method in my connector. This my code:
public class MQTTConnector {
private MqttAsyncClient mClient;
private IMqttToken mTokenConnect;
private IMqttToken mTokenDisconnect;
private class MqttEventCallback implements MqttCallback {
@Override
public void connectionLost(Throwable cause) {
Log.i(TAG,"Connection lost, cause is " + cause.toString());
cause.printStackTrace();
}
@Override
public void deliveryComplete(IMqttDeliveryToken deliveryToken) {
if (deliveryToken.getException()!=null) {
MqttException me = (MqttException) deliveryToken.getException();
me.printStackTrace();
}
}
@Override
public void messageArrived(String topic, final MqttMessage msg) throws Exception {
try {
String messageText = new String(msg.getPayload(),ENCODING);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
public void connectToLocal(AppClient appClient){
String broker;
clientId = MqttClient.generateClientId();
MemoryPersistence persistence = new MemoryPersistence();
broker = "tcp://localhost:1883";
try {
mClient = new MqttAsyncClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setUserName(mAppClient.getUser());
String pass = Command.createHashString(mAppClient.getPassword(),"SHA-256");
connOpts.setPassword(pass.toCharArray());
mTokenConnect = mClient.connect(connOpts);
mTokenConnect.waitForCompletion(3500);
registeredCallback = new MqttEventCallback(false);
mClient.setCallback(registeredCallback);
} catch (MqttException me) {
me.printStackTrace();
}
}
private class DisconnectedCallback implements IMqttActionListener {
@Override
public void onSuccess(IMqttToken disconnectedToken) {
Log.i(TAG, "Mqtt client " + clientId + " was disconnected successfully");
registeredCallback = null;
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
}
public void disconnect(int graceTimeout) {
try {
mTokenDisconnect = mClient.disconnect(graceTimeout,null,new DisconnectedCallback());
mTokenDisconnect.waitForCompletion();
mClient.close();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
It works basically, if I call for example disconnect(1000), then I need to stop broker on localhost, but every time when MQTT broker on localhost is shut down in log I see the message: "Connection lost, cause is ...", for me it means, that callback thread was. My question is why thread with callback MqttEventCallback is alive after disconnect() method was completed? What is wrong in call sequence in disconnect method?
Best regards,
Nicolay Sergeev