Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Node.js Socket.io not connecting

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)

like image 776
Melanie Journe Avatar asked Nov 26 '22 23:11

Melanie Journe


1 Answers

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

like image 102
Paco Cubel Avatar answered Dec 04 '22 10:12

Paco Cubel