简体   繁体   中英

Cannot connect to socket with Android App

I spent more 1 day to try to connect from Android App to SocketIO but can not. 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. This is dependencies I added in 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 :


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

To allow http, edit your AndroidManifest.xml and add android:usesCleartextTraffic="true" to application tag like this

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

▲ this answer if it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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