0

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.
abhinay
  • 3
  • 6
  • what is shown in the logcat? – Sairaj Sawant Jun 09 '20 at 03:24
  • @SairajSawant There aren't any errors or exceptions. Debug line I added has is last line. `The ClassLoaderContext is a special shared library. I/Perf: Connecting to perf service. W/example.tambol: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection) W/example.tambol: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection) *D/socket status: false*` – abhinay Jun 09 '20 at 07:12

0 Answers0