abhinay
abhinay

Reputation: 3

Unable to connect to node.js server from Android client using socket.io

I have implemented every step mentioned in the socket.io website but not sure why I am unable to connect to the Node.js server from my Android application. Below are the files I have used for implementation.

Package.json

{
    "name": "First application"
    "version": "1.0.0",
    "description": "My First Android Application",
    "main": "server.js",
    "dependencies": {
        "express": "^4.17.1",
        "socket.io": "^2.3.0"
        "socket.io-client": "^2.3.0"        
    }
}

Index.js(server file)

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

app.get('/',(req,res) => {
    res.send('Server is running on port 3000');
});

io.on('connection',(socket) => {
    console.log('Device connected');
    socket.on('foo',(request) => {
        console.log('Received foo from host');
    });
});

server.listen(3000,() => {
    console.log('listening to port:3000');
});

Client code

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

public class MainActivity extends AppCompatActivity {

    Socket socket;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            socket = IO.socket("http://192.168.xx.xx:3000/");
            socket.on(Socket.EVENT_CONNECT,  new Emitter.Listener() {

                @Override
                public void call(Object... args) {
                    Log.d("TAG", "Socket Connected!");
                }

            });

            Log.d("socket status",String.valueOf(socket.connected()));
        }
        catch (URISyntaxException e){
            e.printStackTrace();
        }
}
}

build.gradle(: app) added below part in Gradle dependencies

    implementation ('io.socket:socket.io-client:1.0.0'){
        exclude group: 'org.json',module:'json'
    }
  1. I am able to access 192.168.xx.xx:3000 from my mobile. Mobile and laptop are in the same wifi network.
  2. Socket.connected() returning false.
  3. "Socket Connected!" is also not getting logged. Let me know if something else is needed for analysis.

Upvotes: 0

Views: 399

Answers (0)

Related Questions