【问题标题】:ANDROID-MQTT :Unable to connect to server (32103)ANDROID-MQTT:无法连接到服务器 (32103)
【发布时间】:2017-04-20 08:46:40
【问题描述】:

我正在尝试学习 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());
        }


    }
    }

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

【问题讨论】:

  • 错误表示连接被拒绝,这意味着代理未在该端口上侦听。使用代理如何配置的详细信息更新问题

标签: android mqtt mosquitto paho


【解决方案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 子客户端并查看您是否收到消息。

希望有帮助!

【讨论】:

    【解决方案2】:

    尝试使用端口 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();
    }
    

    【讨论】:

    • 除非我们知道代理是如何配置的,否则仅仅选择一个不同的端口并没有帮助。您似乎也将代理更改为公共代理,如果 OP 想要运行自己的代理,这将无济于事
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多