mqttexception(0)-java.net.sockettimeoutexception:无法连接到/192.168.1.xx(port 1883)30000ms之后的/10.0.2.xx(port xxxxx)

发布于 2025-01-20 15:24:44 字数 10699 浏览 3 评论 0 原文

我对Android开发的MQTT非常陌生。因此,我做了类似于本指南的事情。

我试图将我的Android应用程序从Android Studio Emulator连接到MQTT经纪人。该经纪人位于我的Windows10笔记本电脑(与Android客户端相同的机器)中。我发现的问题是我的Android客户端无法将自己连接到MQTT代理IP。我以多种方式尝试了它,但仍然无法正常工作。所以,我不确定我是否做对吗?

这是我的 build.gradle

dependencies {
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
    implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
}

我的设置中的依赖项。

(应该在 build.gladle 文件中在我第一次尝试时,有一种编译应用程序的方式,它显示了“同步错误”。 。)

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()

        maven {
            url "https://repo.eclipse.org/content/repositories/paho-releases/"
        }
    }
}

androidmanifest.xml ,我包括了一些许可 android Service

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.smartmousetrap">

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.SmartMouseTrap">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name="org.eclipse.paho.android.service.MqttService"/>

    </application>

</manifest>

这是首先具有连接问题的所有 mainActivity.java

public class MainActivity extends AppCompatActivity {

    private Button buttonConnect;

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

        buttonConnect = findViewById(R.id.buttonConnect);
        buttonConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String clientId = MqttClient.generateClientId();
                Toast.makeText(MainActivity.this, clientId, Toast.LENGTH_SHORT).show();
                MqttAndroidClient client = new MqttAndroidClient(MainActivity.this, "tcp://192.168.1.43:1883", clientId);

                try {
                    IMqttToken token = client.connect();
                    token.setActionCallback(new IMqttActionListener() {
                        @Override
                        public void onSuccess(IMqttToken asyncActionToken) {
                            Log.d("Debug", "onSuccess");
                            Toast.makeText(MainActivity.this, "onSuccess", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                            Log.d("Debug", "onFailure");
                            Toast.makeText(MainActivity.this, "onFailure", Toast.LENGTH_SHORT).show();
                            exception.printStackTrace();
                        }
                    });
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

,我使用此变量引用该按钮。单击按钮时,应用程序将自身连接到MQTT代理。

buttonConnect = findViewById(r.id.buttonConnect);

buttonConnect.setOnClickListener(new View.OnClickListener(){...}){...})

========================================== =================================

'192.168.1.43'是我的笔记本电脑IP(Broker)

mqttandroidclient客户端=新的mqttandroidclient(mainActivity.this,“ tcp://192.168.1.43:1883”,clientid);

========================================================================================== =========================

它尝试了“ client.connect”后,它最终进入了此“ Failure”部分。

imqtttoken token = client.connect();

try {
    IMqttToken token = client.connect();
    token.setActionCallback(new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken asyncActionToken) {
            Log.d("Debug", "onSuccess");
            Toast.makeText(MainActivity.this, "onSuccess", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            Log.d("Debug", "onFailure");
            Toast.makeText(MainActivity.this, "onFailure", Toast.LENGTH_SHORT).show();
            exception.printStackTrace();
        }
    });
} catch (MqttException e) {
    e.printStackTrace();
}

这是我遇到的 mqttexception 提示的错误。

请注意, 10.0.2.16 是我的Android IP(来自Android Studio Emulator),

D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0x75161b0e2c50, tid 7084
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2 
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
W/OpenGLRenderer: Failed to initialize 101010-2 format, error = EGL_SUCCESS
D/EGL_emulation: eglCreateContext: 0x75161b0e2650: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0x75161b0e2650: ver 2 0 (tinfo 0x751835ee2080) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0x75161b0e2110, tid 7084
D/goldfish-address-space: allocate: Ask for block of size 0x100
D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3efffe000 size 0x2000
W/Gralloc4: allocator 4.x is not supported
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2 
W/System: A resource failed to call close. 
D/EGL_emulation: app_time_stats: avg=409.15ms min=4.48ms max=3278.83ms count=9
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10166; state: ENABLED
D/AlarmPingSender: Unregister alarmreceiver to MqttServicepaho3870573646500
D/AlarmPingSender: Unregister alarmreceiver to MqttServicepaho3870573646500
D/Debug: onFailure
W/System.err: MqttException (0) - java.net.SocketTimeoutException: failed to connect to /192.168.1.43 (port 1883) from /10.0.2.16 (port 56170) after 30000ms
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:664)
W/System.err:     at java.lang.Thread.run(Thread.java:920)
W/System.err: Caused by: java.net.SocketTimeoutException: failed to connect to /192.168.1.43 (port 1883) from /10.0.2.16 (port 56170) after 30000ms
W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:236)
W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:180)
W/System.err:     at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:142)
W/System.err:     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
W/System.err:     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
W/System.err:     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
W/System.err:     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
W/System.err:     at java.net.Socket.connect(Socket.java:621)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:70)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)
W/System.err:   ... 1 more

如果我做错了什么或任何建议,请提供帮助。

I am very new to the mqtt on Android Development. So, I did something similar to this guide.
https://www.hivemq.com/blog/mqtt-client-library-enyclopedia-paho-android-service/

I have tried to connect my android application from the Android Studio emulator to Mqtt broker. The broker is located in my Windows10 laptop (which is the same machine as the Android client). The problem I found is that my Android client cannot connect itself to the Mqtt broker ip. I've tried it in many ways but still couldn't get it work. So, I'm not sure if I'm doing it right?

Here is my build.gradle dependencies

dependencies {
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
    implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
}

In my setting.gladle file, I've added maven repository as below.

(This supposed to be in the build.gladle file, but I did it this way because I found out that build.gladle in the newer version of android studio has a different way to compile the app. When I first tried on that, it shows the message that 'syncing error'. So, I've included in the setting.gladle instead, to avoid that error.)

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()

        maven {
            url "https://repo.eclipse.org/content/repositories/paho-releases/"
        }
    }
}

The AndroidManifest.xml, I have included some permission and android service.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.smartmousetrap">

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.SmartMouseTrap">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name="org.eclipse.paho.android.service.MqttService"/>

    </application>

</manifest>

And this is all of the MainActivity.java where it has the connection problem

public class MainActivity extends AppCompatActivity {

    private Button buttonConnect;

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

        buttonConnect = findViewById(R.id.buttonConnect);
        buttonConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String clientId = MqttClient.generateClientId();
                Toast.makeText(MainActivity.this, clientId, Toast.LENGTH_SHORT).show();
                MqttAndroidClient client = new MqttAndroidClient(MainActivity.this, "tcp://192.168.1.43:1883", clientId);

                try {
                    IMqttToken token = client.connect();
                    token.setActionCallback(new IMqttActionListener() {
                        @Override
                        public void onSuccess(IMqttToken asyncActionToken) {
                            Log.d("Debug", "onSuccess");
                            Toast.makeText(MainActivity.this, "onSuccess", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                            Log.d("Debug", "onFailure");
                            Toast.makeText(MainActivity.this, "onFailure", Toast.LENGTH_SHORT).show();
                            exception.printStackTrace();
                        }
                    });
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

First, I reference to the button using this variable. When the button get clicked, the application will connect itself to the Mqtt broker.

buttonConnect = findViewById(R.id.buttonConnect);

buttonConnect.setOnClickListener(new View.OnClickListener() {...})

===========================================

'192.168.1.43' is my laptop ip (broker)

MqttAndroidClient client = new MqttAndroidClient(MainActivity.this, "tcp://192.168.1.43:1883", clientId);

===========================================

After it tried 'client.connect', it ended up in this 'onFailure' section.

IMqttToken token = client.connect();

try {
    IMqttToken token = client.connect();
    token.setActionCallback(new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken asyncActionToken) {
            Log.d("Debug", "onSuccess");
            Toast.makeText(MainActivity.this, "onSuccess", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            Log.d("Debug", "onFailure");
            Toast.makeText(MainActivity.this, "onFailure", Toast.LENGTH_SHORT).show();
            exception.printStackTrace();
        }
    });
} catch (MqttException e) {
    e.printStackTrace();
}

This is the MqttException prompted error I've got.

Note that 10.0.2.16 is my android ip (from Android Studio emulator)

D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0x75161b0e2c50, tid 7084
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2 
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
W/OpenGLRenderer: Failed to initialize 101010-2 format, error = EGL_SUCCESS
D/EGL_emulation: eglCreateContext: 0x75161b0e2650: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0x75161b0e2650: ver 2 0 (tinfo 0x751835ee2080) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0x75161b0e2110, tid 7084
D/goldfish-address-space: allocate: Ask for block of size 0x100
D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3efffe000 size 0x2000
W/Gralloc4: allocator 4.x is not supported
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2 
W/System: A resource failed to call close. 
D/EGL_emulation: app_time_stats: avg=409.15ms min=4.48ms max=3278.83ms count=9
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10166; state: ENABLED
D/AlarmPingSender: Unregister alarmreceiver to MqttServicepaho3870573646500
D/AlarmPingSender: Unregister alarmreceiver to MqttServicepaho3870573646500
D/Debug: onFailure
W/System.err: MqttException (0) - java.net.SocketTimeoutException: failed to connect to /192.168.1.43 (port 1883) from /10.0.2.16 (port 56170) after 30000ms
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:664)
W/System.err:     at java.lang.Thread.run(Thread.java:920)
W/System.err: Caused by: java.net.SocketTimeoutException: failed to connect to /192.168.1.43 (port 1883) from /10.0.2.16 (port 56170) after 30000ms
W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:236)
W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:180)
W/System.err:     at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:142)
W/System.err:     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
W/System.err:     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
W/System.err:     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
W/System.err:     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
W/System.err:     at java.net.Socket.connect(Socket.java:621)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:70)
W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:650)
W/System.err:   ... 1 more

If I done anything wrong or any suggestion please help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

可是我不能没有你 2025-01-27 15:24:44

以下内容类似于:

如何在 Android 模拟器中连接 localhost?

您可能需要访问经纪人:

10.0.2.2:1883

Following something like:

How do you connect localhost in the Android emulator?

you probably need to access the broker on:

10.0.2.2:1883

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文