MClt
MClt

Reputation: 53

Can not connect between android device and node.js server

So here, I'm trying to connect my android to my server node.js, using the socket.io but during the execution, there is no error but the connection has not been established and returns me false

Thank you in advance for your help !

Socket.Java

package com.example.myprojectapplication.ObjectClass;

import com.github.nkzawa.socketio.client.IO;

import java.net.URISyntaxException;

public class Socket {

    private com.github.nkzawa.socketio.client.Socket mSocket;
    {
        try {
            mSocket = IO.socket("localhost:8081/");
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    public com.github.nkzawa.socketio.client.Socket getSocket() {
        return mSocket;
    }
}

Relevant part of my MainActivity

com.example.myprojectapplication.ObjectClass.Socket app = new com.example.myprojectapplication.ObjectClass.Socket();
Socket mSocket = app.getSocket();
mSocket.connect();

Node.js Server

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

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

  socket.emit('message', 'Android Connected');
  console.log("Android Connected");

  socket.on('message', function(message){
    console.log("message received");
    socket.emit('message', 'message received');
  });

});

server.listen(8081)

Upvotes: 4

Views: 2328

Answers (2)

Rick Sanchez
Rick Sanchez

Reputation: 4746

The other answer is correct. But one other thing to note : if you are using an emulator, then you can use 10.0.2.2 to refer to the localhost of the host computer. This is very useful for development because you won't have to get the actual IP addresses of your laptop each time you change the network.

See :https://developer.android.com/studio/run/emulator-networking for more info

Upvotes: 2

Shailesh Bhokare
Shailesh Bhokare

Reputation: 592

In Socket.Java your using localhost:8081/ Instead of this address you have to use node.js server IP address (Local IP address). To connect your application with node.js server you have to keep your computer and application running device in same network.

Upvotes: 3

Related Questions