Android Studio 无法连接到套接字,IO使用Socket,IO客户端Java

neekobn8  于 2022-11-16  发布在  Android
关注(0)|答案(1)|浏览(191)

我尝试使用工具http://amritb.github.io/socketio-client-tool/v1/连接到已知已启动并正在运行的套接字
我正在使用Android Studio构建一个Android应用程序。我已经在清单文件中添加了INTERNET权限,并将Socket.IO-client放在gradle中

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="poly.project3.test">
    <uses-permission android:name="android.permission.INTERNET" />
    <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.Test">
        <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>
    </application>

</manifest>

dependencies {
    implementation ('io.socket:socket.io-client:2.0.0') {
        exclude group: 'org.json', module: 'json'
    }
    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'
}

下面是我尝试运行的简单代码:

package poly.project3.test;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import java.net.URISyntaxException;

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

public class MainActivity extends AppCompatActivity {

    private Socket mSocket;
    {
        try {
            mSocket = IO.socket("http://public Ip addresse that works:3000");
        } catch (URISyntaxException e) {}
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSocket.connect();
        System.out.println(mSocket.connected());
    }
}

我没有得到任何错误,但mSocket.connected()返回False。此外,在服务器日志中没有新的套接字连接

k5hmc34c

k5hmc34c1#

赫卢
在android清单中使用此

<application
   ....
    android:networkSecurityConfig="@xml/network_security_config"
    >

然后在res/xml目录中创建名为network_security_config. xml的文件contents

<?xml version="1.0" encoding="utf-8"?><network-security-config>
<base-config cleartextTrafficPermitted="true">
    <trust-anchors>
        <certificates src="system" />
    </trust-anchors>
</base-config>

相关问题