eclipse / paho.mqtt.java

Eclipse Paho Java MQTT client library. Paho is an Eclipse IoT project.
https://eclipse.org/paho
Other
2.08k stars 879 forks source link

When the mqttv3 client connects() to a server where the message broker is not operating, it does not throw an exception. #1020

Open angryEK opened 7 months ago

angryEK commented 7 months ago

Please fill out the form below before submitting, thank you!

public class Test {
    public static void main(String[] args) throws IOException, MqttException {

        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName("test");
        mqttConnectOptions.setPassword("test".toCharArray());
        mqttConnectOptions.setCleanSession(true);
        mqttConnectOptions.setKeepAliveInterval(30);
        mqttConnectOptions.setConnectionTimeout(2);

        MqttAsyncClient mq = new MqttAsyncClient("tcp://127.0.0.1:61611","test", new MemoryPersistence());

        try {
            IMqttToken token = mq.connect(mqttConnectOptions);
            Thread.sleep(5000);
            System.out.println(token.isComplete());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The above example is a code that makes a connect request to any server without a message broker.

If you follow the code inside the library(package org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule(line:67 start())

    public void start() throws IOException, MqttException {
        final String methodName = "start";
        try {
            // @TRACE 252=connect to host {0} port {1} timeout {2}
            log.fine(CLASS_NAME,methodName, "252", new Object[] {host, Integer.valueOf(port), Long.valueOf(conTimeout*1000)});
            SocketAddress sockaddr = new InetSocketAddress(host, port);
            socket = factory.createSocket();
            socket.connect(sockaddr, conTimeout*1000);
            socket.setSoTimeout(1000);
        }
        catch (ConnectException ex) {
            //@TRACE 250=Failed to create TCP socket
            log.fine(CLASS_NAME,methodName,"250",null,ex);
            throw new MqttException(MqttException.REASON_CODE_SERVER_CONNECT_ERROR, ex);
        }
    }

you will call Socket connect. Socket connect() for non-operating servers will cause ConnectException. On the code, the generated ConnectException is thrown as MqttException. But I can't get any reception, the project I made doesn't work normally. Am I misunderstanding and using it?