2

I have made a basic nodejs server that console logs when a user connects to the server. i am using socket io for this because i wanna make a chat application. On my android side im trying to create a connection to this local server but i never get the console log when i try and socket.connected stays on false. also never get a error or something when trying to connect

I have tried some examples from the internet. i got 1 example working deleted everything that i didnt use and it still works. i copy paste from that example to my own project and still didn't work. This is the example i used.

Here is the code of my project Node JS:

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

Android:

public class MainActivity extends Activity {
    private Socket socket;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ChatApplication app = (ChatApplication) getApplication();
        socket = app.getSocket();
        socket.connect();
    }
}

ChatApplication class:

public class ChatApplication extends Application {
    private Socket mSocket;
    {
        try {
            mSocket = IO.socket("http://192.168.0.109:3000");
        } catch (Exception e) {
            Log.e("Error", e.toString());
        }
    }

    public Socket getSocket() {
        return mSocket;
    }
}
Deˣ
  • 4,191
  • 15
  • 24
Michael
  • 33
  • 4

1 Answers1

0

Android Studio emulator usually prevents localhost connections, I'm not sure if this happened in your case, but it has happened to me. Try popping out your Logcat in Android Studio and see if you can find something that indicates that the localhost connection got denied.

Not sure if this is it, but you should check.

LoopsGod
  • 371
  • 2
  • 11