4

I have a Node.js server using socket.io and an android app. I want my app to connect to the server. (I work locally)

So first I start the server : command prompt

Here is the code of it :

var express    = require('express');        // call express
var app        = express();  
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 1234;


app.get('/',function(req,res){
    res.send("Welcome to my socket");
});


io.on('connection', function (socket) {

    console.log('one user connected : '+socket.id);

    // when the client emits 'new message', this listens and executes
    socket.on('new message', function (data) {
        // we tell the client to execute 'new message'
        console.log('this is message :',data);
    });

});


http.listen(port, function () {
  console.log('Server listening at port %d', port);
});

And then I try to connect from my activity here :

public class AvisActivity extends AppCompatActivity {

  private Socket mSocket;
    {
        try {
            mSocket = IO.socket("http://172.21.191.234:1234");
        } catch (URISyntaxException e) { Log.v("AvisActivity", "error connecting to socket");}
    }

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


        Log.v("AvisActivity", "try to connect");
        mSocket.connect();
        Log.v("AvisActivity", "connection sucessful");

    }
}

My problem is that I never see the log "one user connected" on the server but I always see the "try to connect" and " connection sucessful" on the android log.

Can someone solve this mystery for my please ?

UPDATE

My code worked fine, but I encounter some Wifi configuration that blocks web socket (and actually my school did, that's where my problems came from)

Melanie Journe
  • 1,249
  • 5
  • 16
  • 36

7 Answers7

25

In the latest versions of Android, you need to add AndroidManifest.xml "android: usesCleartextTraffic = true" to allow connections with plain text.

Example:

<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/AppTheme"
    android:usesCleartextTraffic="true">

Android Developers > Docs > Guías - Link

Paco Cubel
  • 387
  • 3
  • 7
13

For API 23 and higher, you have to add android:usesCleartextTraffic="true" in your manifest file.

Hashir Sarwar
  • 1,115
  • 2
  • 14
  • 28
7

For anyone else googling here, this helped me get some log information about the problem:

Log.v("AvisActivity", "try to connect");
mSocket.connect();

mSocket.io().on(Manager.EVENT_TRANSPORT, new Emitter.Listener() {
    @Override
    public void call(Object... args) {
        Transport transport = (Transport) args[0];
        transport.on(Transport.EVENT_ERROR, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                Exception e = (Exception) args[0];
                Log.e(TAG, "Transport error " + e);
                e.printStackTrace();
                e.getCause().printStackTrace();
            }
        });
    }
});

For me, the issue is that the client won't use TLSv1.1 or 1.2. I haven't figured it out as of this writing. Making my server support TLSv1.0 is my current workaround.

ki9
  • 5,183
  • 5
  • 37
  • 48
  • For me, the error was "Cleartext HTTP traffic not permitted" - and I couldn't have reached there without your snippet! Thank you so much. – Nikhil Baliga Apr 18 '19 at 14:24
2

Put your socket initializing code inside your onCreate method like below:

public class AvisActivity extends AppCompatActivity {

  private Socket mSocket;

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

        try {
            mSocket = IO.socket("http://172.21.191.234:1234");
        } 
        catch (URISyntaxException e) { 
            Log.v("AvisActivity", "error connecting to socket");
        }

        Log.v("AvisActivity", "try to connect");
        mSocket.connect();
        Log.v("AvisActivity", "connection sucessful");

    }
}
Prerak Sola
  • 9,517
  • 7
  • 36
  • 67
2

you code is fine it's working properly, you need to only confirm IP address which you are connecting is right and also INTERNET permission added in manifest.xml

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

enter image description here

Rohit Patil
  • 1,068
  • 8
  • 9
0

UPDATE

My code worked fine, but I encounter some Wifi configuration that blocks web socket (and actually my school did, that's where my problems came from). But I don't really know how they blocked it.

Also, later in my project when I deploy to an OVH server, I got problems by using the 1234 port. Make sure to use a port available/unlocked by your provider.

Melanie Journe
  • 1,249
  • 5
  • 16
  • 36
-1

Worked for me with this single line:

opts.transports = new String[]{"websocket"};

https://stackoverflow.com/a/67978895/6909832

Matheus Santz
  • 538
  • 6
  • 7