Establishing Socket.IO Connection from Android Device to Local Node Server
A. Make sure you've installed socket.io-client-java via gradle.
B. Make sure you've enable internet access for your device.
<!-- AndroidManifest.xml -->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="...">
<uses-permission android:name="android.permission.INTERNET" />
<application ...>
...
</application>
</manifest>
C. Make sure the port you're running the server on is open.
D. Connect to your local server using your computers network ip address.
- Open a terminal.
- Enter the command
ipconfig
.
- Look for your IPv4 Address.
You want to connect to http://<IPv4 Address>:<port>
.
Connecting to localhost via http://localhost:3000
will not work because 'localhost' refers to the device itself.
E. Test the connection on your device.
- Set up a simple route on your server
GET /status
that just returns 200.
- Navigate to
http://<IPv4 Address>:<port>/status
on your device.
- If you get a success response, you should be good to go.
F. You should now be able to connect your android socket client to your node socket server.
// Node.js App
let SocketIO = require('socket.io');
let ioServer = SocketIO(server);
console.log('Socket Server waiting for connections');
ioServer.on('connection', function (socket) {
console.log(`Socket Client connected with id=${socket.id}`);
});
-
// Android App
import io.socket.client.Socket;
import io.socket.client.IO;
import io.socket.emitter.Emitter;
import android.util.Log;
public class SocketIO implements Runnable {
@Override
public void run() {
final Socket socket;
try {
socket = IO.socket("http://<IPv4 Address>:<port>");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.d("TAG", "Socket Connected!");
socket.disconnect();
}
});
} catch(Exception e){
Log.e("Error", e.toString());
}
}
}