I have a backend written with express and an app with Java for android.
Background:
I want to create socket communication between the app and the server, but I can't connect to the server from the app.
The backend side is fully tested, and I can send requests from postman and receive data as well. This is the code inside the server that handles the socket:
import { Server } from "socket.io";
import { SOCKET_EVENTS } from "../../constants/socket.js";
import { getBlockchainBlock } from "../crypto/crypto.js";
const io = new Server(4000, {
cors: {
origin: "*",
},
});
export const openSocket = () => {
io.on(SOCKET_EVENTS.CONNECTION, async (socket) => {
console.log("user connected! socket id:", socket.id);
io.emit(SOCKET_EVENTS.NEW_TASK, {
data: await getBlockchainBlock(),
});
socket.on(SOCKET_EVENTS.TASK_FINISHED, (data) => {
console.log("User task is done with data:", data);
});
socket.on(SOCKET_EVENTS.DISCONNECT, () => {
console.log("user disconnected! socket id:", socket.id);
});
});
};
Android side
I added the socket.io-client
library to the android app:
implementation ('io.socket:socket.io-client:2.0.0') {
exclude group: 'org.json', module: 'json'
}
My attempt to add the socket library in order to communicate with the server:
public class MainActivity extends AppCompatActivity {
Socket mSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.test);
textView.setText("Some test");
Emitter.Listener onNewTask = new Emitter.Listener() {
@Override
public void call(final Object... args) {
}
};
Emitter.Listener taskFinished = new Emitter.Listener() {
@Override
public void call(final Object... args) {
mSocket.emit("taskFinished", "Task is finished");
}
};
try {
mSocket = IO.socket("http://ipAddress:4000");
mSocket.on("newTask", onNewTask);
mSocket.on("connection", new Emitter.Listener() {
@Override
public void call(Object... args) {
System.out.println("Connected to server!");
}
});
mSocket.on("taskFinished", taskFinished);
mSocket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
The problem:
I cant see the Connected to server!
print, when I used a debugger to debug the app the mSocket.connect();
line was called but there was never a connection.
In addition - I can see in the backend prints for new connection when trying it via postman, but nothing shows when running the android code (seems like there is no connection)
Getting the IP address
The server is sitting on http://localhost:4000
, according to this thread I needed to replace localhost
with the IP address.
To do so I opened up cmd and run the ipconfig
command and replaced localhost
with IPv4 Address
Extra info
Those are the constants names I am using inside the server:
export const SOCKET_EVENTS = {
CONNECTION: "connection",
NEW_TASK: "newTask",
TASK_FINISHED: "taskFinished",
DISCONNECT: "disconnect",
};