Synch and Asynchronous interface of MqttClient object are not working
Asked Answered
O

2

16

I have created a client of type MqttClient and as shown below in the code, I create a client and se its Asynchronous callback. The problem is,

1-when I run the programm, the System.out.println("Client is Connected"); appears, but i receive no response fr0m the onSuccess or from oonFailure, why? wha I am doing wrong in the code.

2-i implemented the static IMqttAsyncClient asynchClientCB = new IMqttAsyncClient() interface, but since i have a client of type MqttClient, I can not use this IMqttAsyncClient interface. I tried to use mqttAsynchClien but because I program for java and not for Android i can not use it. How to use IMqttAsyncClient interface.?

Update_1

in the below code "Updated_code_1", i slightly modified the code, but i expect every time i connect successfully to the broker the message in onSuccess synchronous callback to be printed, and the message in onFailure synchronous callbck to be printed in case of the onnection terminated such as when i intentionally disconnect the network. But at ru time when I connect to the broker, neither onSuccess nor onFailur dispays any thing. So, what are they designed for?

*Update_2_17_Dec_2014

I have an inquiry that might lead us to a solution, which is, does it matter if I am connecting to the broker through wired/wire-less network? would that change the behaviour of he synchronous and Asynchronous listener?

Updated_1_code:

MqttConnectOptions opts = getClientOptions();
        client = MQTTClientFactory.newClient(broker, port, clientID);

        if (client != null) {
            System.out.println("Client is not Null");
            client.setCallback(AsynchCallBack);
            if (opts != null) {
                iMQTTToken = client.connectWithResult(opts);
                publishMSG(client, TOPIC,"010101".getBytes(), QoS, pub_isRetained);
                iMQTTToken.setActionCallback(synchCallBack);
                if (client.isConnected()) {
                    System.out.println("Client CONNECTED.");
                    publishMSG(client, TOPIC,"010101".getBytes(), QoS, pub_isRetained);
                }
            }
        }
    ....
    ....
    ....
    ....
IMqttToken iMQTTToken = new IMqttToken() {

    @Override
    public void waitForCompletion(long arg0) throws MqttException {
        // TODO Auto-generated method stub
        System.out.println("@waitForCompletion(): waiting " + (arg0 * 1000) + " seconds for connection to be established.");
    }

    @Override
    public void waitForCompletion() throws MqttException {
        // TODO Auto-generated method stub
        System.out.println("@waitForCompletion(): waiting for connection to be established.");
    }

    @Override
    public void setUserContext(Object arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void setActionCallback(IMqttActionListener arg0) {
        // TODO Auto-generated method stub
        arg0.onSuccess(iMQTTToken);
        //System.out.println(" " + arg0.onSuccess());
        //System.out.println(" " + arg0.onSuccess(iMQTTToken));
        iMQTTToken.setActionCallback(synchCallBack);
    }

    @Override
    public boolean isComplete() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public Object getUserContext() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String[] getTopics() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean getSessionPresent() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public MqttWireMessage getResponse() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int getMessageId() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public int[] getGrantedQos() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public MqttException getException() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public IMqttAsyncClient getClient() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public IMqttActionListener getActionCallback() {
        // TODO Auto-generated method stub
        return null;
    }
};

IMqttActionListener synchCallBack = new IMqttActionListener() {

    @Override
    public void onSuccess(IMqttToken arg0) {
        // TODO Auto-generated method stub
        System.out.println("@onSuccess: Connection Successful.");
    }

    @Override
    public void onFailure(IMqttToken arg0, Throwable arg1) {
        // TODO Auto-generated method stub
        System.out.println("@onFailure: Connection Failed.");
        setViewEnableState(Bconnect, true);
    }
};

MqttCallback AsynchCallBack = new MqttCallback() {

    @Override
    public void messageArrived(String topic, MqttMessage msg) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("@messageArrived: Message Delivered.");
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        // TODO Auto-generated method stub
        System.out.println("@deliveryComplete: Delivery Completed.");
    }

    @Override
    public void connectionLost(Throwable thrw) {
        // TODO Auto-generated method stub
        System.out.println("@Connection Lost: Connection Lost.");
        setViewEnableState(Bconnect, true);
    }
};

Newclient:

    MqttConnectOptions opts = new MqttConnectOptions();
    opts.setCleanSession(CS);
    opts.setKeepAliveInterval(KATimer);
    HashMap<Integer, WILL> LWTData = WILLFactory.newWILL("LWT", "LWT MS".getBytes(), 1, false);
    opts.setWill(LWTData.get(0).getWILLTopic(), 
            LWTData.get(0).getWILLPayLoad(), 
            LWTData.get(0).getWILLQoS(), 
            LWTData.get(0).isWILLRetained());

    client = MQTTClientFactory.newClient(IP, PORT, clientID);

    if (client != null) {
        System.out.println("client is not null");

        client.setCallback(AsynchCB);
        IMqttToken token = client.connectWithResult(opts);

        if (client.isConnected()) {
            System.out.println("Client is Connected");

            token.setActionCallback(new IMqttActionListener() {

                public void onSuccess(IMqttToken arg0) {
                    // TODO Auto-generated method stub
                    System.out.println("synchCB->@onSuccess(): Connection Successful");

                    try {
                        client.subscribe(TOPIC, QoS);
                    } catch (MqttException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    try {
                        client.disconnect();
                    } catch (MqttException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                public void onFailure(IMqttToken arg0, Throwable arg1) {
                    // TODO Auto-generated method stub
                    System.out.println("synchCB->@onFailure(): Connection Failed");
                }
            });
        }else {
            System.out.println("client is not connected");
        }
    }else {
        System.out.println("client = null");
    }

Asynch CallBack:

/**
 * Asynchronous Callback to inform the user about events that might happens Asynchronously. If it is not used, any pending 
 * messages destined to the client would not be received.
 */
private static MqttCallback AsynchCB = new MqttCallback() {

    public void messageArrived(String topic, MqttMessage msg) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("AsynchCB->@messageArrived(): ");

        System.out.println("Topic: " + topic);
        System.out.println("MSG: " + msg.toString());

    }

    public void deliveryComplete(IMqttDeliveryToken arg0) {
        // TODO Auto-generated method stub
        System.out.println("AsynchCB->@deliveryComplete(): ");
    }

    public void connectionLost(Throwable arg0) {
        // TODO Auto-generated method stub
        System.out.println("AsynchCB->@connectionLost(): ");
    }
};
Onlybegotten answered 28/11, 2014 at 9:31 Comment(7)
What happens if you take out the subscription from the onSuccess() and instead add it right after you checked that your connection is successful? What I mean is to put this line client.subscribe(TOPIC, QoS); right after checking that isConnected() returns true. I'm a little confused why you would expect the onSuccess() to be called before you've actually subscribed or done anything with your connection other than setting a callback listener.Griggs
@Griggs thank you for the comment. Actually after reading your comments it seems that i misunderstood what onSuccess and onFailure do. because i think that, onSuccess() and onFailure are synchronous callbacks that are called when connection is successfull"onSuccess" or failed "onFailure", that's why i subscribe inside onSucess(), thinking that when te connection established/successful then do subscribe. I am right or wrong? please guideOnlybegotten
Your connection is already successful and established. You are already correctly checking it in this line: if (client.isConnected()) ... Since you have a working connection, you should be ok to subscribe to your topics. Give it a try and see if the topic subscription works. If so, you should be able to start receiving messages posted on those topics.Griggs
@Griggs [Your connection is already successful and established. You are already correctly checking it in this line: if (client.isConnected())]===> yes, ok i am checking it correctly, but, if the networkconnection happened to unexectedly disconnected and re-connected I do not receive any response from eithe "onSuccess" or "onFailure". AFAIU, the afrementioned synchronous callback are intended o report such actions "connection/disconnection". Kindly please see the update aboveOnlybegotten
the connection type to the network does not matter, I have worked in a GridGain network, with wireless network connection to all nodes, so this should not matter even if the process is async or not.Backhanded
@Backhanded concerning the wirless network, i created an android App that uses Paho Android API to connect to a broker wirelessly and i have not faced any of the problems mentioned in this question, the asynch and synch callbacks responds especially the synchronous one that is intended to report onSuccess and onFailure. when I tried to create a java program whic connects to the broker via wired network i receive no report regarding onsucess and onFailure, that's why I thought it maybe because of the network type "wired one"Onlybegotten
@Griggs and rmaik please help me. #36056881Nephrotomy
B
2

your machine on which resides the client, which process your callback, may have the outgoing port blocked by the machine's firewall.

Backhanded answered 11/12, 2014 at 15:55 Comment(2)
I do not think so, because I can publish normallyOnlybegotten
if your client uses that specific port for outgoing publishing then, you are right if you are not certain, check it please.Backhanded
R
0

If the connection in the previous cycle is not disconnected successfully then another attempt to connection will not provide any response. i.e., If connect called for already connected client then it will not produce any response.

Resolute answered 10/8, 2021 at 5:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.