ANDROID-MQTT:无法连接到服务器(32103)

时间:2017-04-20 08:46:41

标签: android mqtt mosquitto paho

我正在尝试学习Android中的基本MQTT集成。我正在使用mosquitto经纪人发布和订阅消息。我在真实设备上运行代码并获得此异常:

    Unable to connect to server (32103) - java.net.ConnectException: 
    failed to connect to /192.168.0.103 (port 1883) after 
    30000ms: isConnected failed: ECONNREFUSED

这是我的代码:

public class HomeActivity extends AppCompatActivity{

    private MqttAndroidClient client;
    private final MemoryPersistence persistence = new MemoryPersistence();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(this.getApplicationContext(), "tcp://192.168.0.103:1883", "androidSampleClient", persistence);
        mqttAndroidClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                System.out.println("Connection was lost!");
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                System.out.println("Message Arrived!: " + topic + ": " + new String(message.getPayload()));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                System.out.println("Delivery Complete!");
            }
        });

        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setCleanSession(true);

        try {
            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    System.out.println("Connection Success!");
                    try {
                        System.out.println("Subscribing to /test");
                        mqttAndroidClient.subscribe("/test", 0);
                        System.out.println("Subscribed to /test");
                        System.out.println("Publishing message..");
                        mqttAndroidClient.publish("/test", new MqttMessage("Hello world testing..!".getBytes()));
                    } catch (MqttException ex) {

                    }
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    System.out.println("Connection Failure!");
                    System.out.println("throwable: " + exception.toString());
                }
            });
        } catch (MqttException ex) {
            System.out.println(ex.toString());
        }


    }
    }

我尝试过使用不同的端口,但错误是一样的。谁能帮助我做错了什么?

2 个答案:

答案 0 :(得分:1)

当您开始使用时,您需要了解不同的实现是如何工作的。看看我的实现。我为MQTT特定的东西使用了一个单独的类。

<强> MqttUtil.java

public class MqttUtil {
    private static final String MQTT_TOPIC = "test/topic";
    private static final String MQTT_URL = "tcp://localhost:1883";
    private static boolean published;
    private static MqttAndroidClient client;
    private static final String TAG = MqttUtil.class.getName();


    public static MqttAndroidClient getClient(Context context){
        if(client == null){
            String clientId = MqttClient.generateClientId();
            client =  new MqttAndroidClient(context, MQTT_URL, clientId);
        }
        if(!client.isConnected())
            connect();
        return client;
    }

    private static void connect(){
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setCleanSession(true);
        mqttConnectOptions.setKeepAliveInterval(30);

        try{
            client.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Log.d(TAG, "onSuccess");
                }
                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.d(TAG, "onFailure. Exception when connecting: " + exception);
                }
            });
        }catch (Exception e) {
            Log.e(TAG, "Error while connecting to Mqtt broker : " + e);
            e.printStackTrace();
        }
    }

    public static void publishMessage(final String payload){
        published = false;
        try {
            byte[] encodedpayload = payload.getBytes();
            MqttMessage message = new MqttMessage(encodedpayload);
            client.publish(MQTT_TOPIC, message);
            published = true;
            Log.i(TAG, "message successfully published : " + payload);
        } catch (Exception e) {
            Log.e(TAG, "Error when publishing message : " + e);
            e.printStackTrace();
        }
    }

    public static void close(){
        if(client != null) {
            client.unregisterResources();
            client.close();
        }
    }
}

您可以在HomeActivity中使用它。请查看以下内容:

public class HomeActivity extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Get Mqtt client singleton instance
    MqttUtil.getClient(this);

    // Publish a sample message
    MqttUtil.publishMessage("Hello Android MQTT");
    }
}

出于测试目的,请使用您的Mosquitto子客户端,看看您是否收到了消息。

希望有所帮助!

答案 1 :(得分:0)

尝试使用端口8883

    String clientId = MqttClient.generateClientId();
final MqttAndroidClient client =
        new MqttAndroidClient(this.getApplicationContext(), "ssl://iot.eclipse.org:8883",
                              clientId);
try {
    MqttConnectOptions options = new MqttConnectOptions();

        InputStream input =
                this.getApplicationContext().getAssets().open("iot.eclipse.org.bks");

        options.setSocketFactory(client.getSSLSocketFactory(input, "eclipse-password"));


        IMqttToken token = client.connect(options);
        token.setActionCallback(new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                // We are connected
                Log.d(TAG, "onSuccess");

            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                // Something went wrong e.g. connection timeout or firewall problems
                Log.d(TAG, "onFailure");

            }
        });


} catch (MqttException | IOException e) {
    e.printStackTrace();
}