How to use the un-blocking method of MqttClient

2019-03-06 06:50发布

问题:

When I try the below code to connect to the mosquitto broker, as you know, connecting to the broker might takes few seconds/minutes, and during that time when the button pressed to connect, it remains pressed till the connection established and when the connection established the button released back to its normal state. As far as I know, there are two way for connecting a client using paho java API, the blocking method and unblocking method. my question is, how to use the unblocking method? beow is my attempt to use the blocking method

Code_1:

//mqttFactory
public final class MQTTClientFactory {

public static MqttClient newClient(String ip, int port, String clientID) throws MqttException {

    String serverURI = formURI(ip, port);
    MqttClient client = new MqttClient(serverURI, clientID).;
    return client;
}



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) {
                client.connectWithResult(opts).setActionCallback(synchCallBack);
                if (client.isConnected()) {
                    System.out.println("Client CONNECTED.");
                }
            }
        }

回答1:

what button? establishing a connection is almost instantly.

There are asynchronous versions of mqtt. Code samples for that. If you want to make the synchronous non-blocking. You could start it up in another thread.



标签: mqtt paho