如何在 android studio 中将 mosquitto 服务器连接到模拟器

How to connect mosquitto server to emulator in android studio

请帮助我了解如何将 mosquitto 服务器连接到模拟器中的应用程序。 在 windows 中使用 mosquitto 代理。无法使用系统的 IP 地址将 mosquitto 服务器连接到模拟器。我可以在cmd中看到这两个端口作为监听端口。

TCP 127.0.0.1:1883 和 TCP [::1]:1883

我已经在应用程序中添加了 paho 的所有依赖项、库和服务。

String clientId = MqttClient.generateClientId();
                    mqttAndroidClient = new MqttAndroidClient(MainActivity.this, **"tcp://192.168.0.5:1883"**,clientId);
                    mqttAndroidClient.setCallback(new MqttCallback() {
                        @Override
                        public void connectionLost(Throwable cause) {
                            Log.d("MqttConnection", "Connection Lost!");
                        }
            
                        @Override
                        public void messageArrived(String topic, MqttMessage message) throws Exception {
                            Log.d("Message", topic + ":  + " + new String(message.getPayload()));
                        }
            
                        @Override
                        public void deliveryComplete(IMqttDeliveryToken token) {
                            Log.d("Delivery Complete", "Delivery Complete!");
                        }
                    });
            
                    connectButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
                        mqttConnectOptions.setAutomaticReconnect(true);
                        mqttConnectOptions.setCleanSession(false);
                        try {
                            mqttAndroidClient.connect(mqttConnectOptions,null, new IMqttActionListener() {
                                @Override
                                public void onSuccess(IMqttToken asyncActionToken) {
                                    Log.d("Mqtt Connection","Connection Success!");
                                }
                                @Override
                                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                                    Log.d("Mqtt Connection Failure","Failed to connect to: " +serverUri + exception.toString());
                                }
                            });
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                    }
                });

127.0.0.1::1 总是指向机器 运行 有问题的代码,在模拟器的情况下是模拟器而不是主机,模拟器是运行 上。

您可以在此处的文档中找到地址列表:https://developer.android.com/studio/run/emulator-networking

但是 10.0.2.2 是与模拟器主机通信的正确地址。

其次,默认情况下,从 v2.0.0 开始,mosquitto 将仅侦听本地主机,并且不允许没有 username/password 的连接。您需要传递配置文件以启用绑定到询问接口并允许匿名连接的侦听器。

确保您阅读了 v2.0.0 版本 notes