简体   繁体   English

无法使用 Android 应用程序连接到套接字

[英]Cannot connect to socket with Android App

I spent more 1 day to try to connect from Android App to SocketIO but can not.我花了更多时间尝试从 Android App 连接到 SocketIO 但不能。 Although I can access to link local by browser in laptop and my physic device (used <uses-permission android:name="android.permission.INTERNET"/> ), I can not connect to Socket by Android App after each times I start application.虽然我可以通过笔记本电脑和物理设备中的浏览器访问本地链接(使用<uses-permission android:name="android.permission.INTERNET"/> ),但每次启动后我都无法通过 Android App 连接到 Socket应用。 This is dependencies I added in gradle :这是我在gradle添加的依赖项:

dependencies{
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
    testImplementation 'junit:junit:4.+'
    implementation ('io.socket:socket.io-client:2.0.0') {
        exclude group: 'org.json', module: 'json'
    }
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

This is my code in MainActivity.java :这是我在MainActivity.java中的代码:


import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import io.socket.client.IO;
import io.socket.client.Socket;

import java.net.URISyntaxException;



public class MainActivity extends AppCompatActivity {
    private Socket mSocket;
    {
        try {
            mSocket = IO.socket("http://192.168.1.2:3000/");
        } catch (URISyntaxException e) {
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSocket.connect();
    }
}

What should I do?我应该怎么办?

You are using a http url for connection On newer android versions http traffic is blocked by default by system您正在使用 http url 进行连接 在较新的 android 版本 Z80791B3AE7002FACB88C246876 系统默认阻止流量

To allow http, edit your AndroidManifest.xml and add android:usesCleartextTraffic="true" to application tag like this要允许 http,请编辑您的 AndroidManifest.xml 并将 android:usesCleartextTraffic="true" 添加到这样的应用程序标签

<application android:usesCleartextTraffic="true">
</application>

▲ this answer if it helps! ▲ 这个答案是否有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM