I'm going to set a simple socket connection between two android devices using internet. There are two devices and two android app's , one of them is client app and another is server app. When the apps run on a device it's all OK, but when the apps run on two devices the client application doesn't connect to server application.
Client app:
btnSend.setOnClickListener(view -> {
String msg = etMessage.getText().toString();
AsyncTask.execute(() -> {
try {
DatagramSocket socket = new DatagramSocket();
InetAddress ip = InetAddress.getByName("100.66.20.245");
int port = 1020;
DatagramPacket packet = new DatagramPacket(
msg.getBytes(), msg.length(), ip, port
);
socket.send(packet);
runOnUiThread(() -> {
Toast.makeText(this, "Message sent", Toast.LENGTH_SHORT).show();
});
} catch (Exception e) {
Log.w(TAG, e.toString());
}
});
});
Server app:
Runnable runnable = () -> {
try {
int port = 1020;
DatagramSocket socket = new DatagramSocket(port);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,1024);
runOnUiThread(() -> {
Toast.makeText(this,"Waiting for client",Toast.LENGTH_SHORT).show();
});
socket.receive(packet);
String msg = new String(packet.getData(),0,packet.getLength());
runOnUiThread(() -> {
Toast.makeText(this, "Client msg : " + msg, Toast.LENGTH_SHORT).show();
});
} catch (Exception e) {
Log.w(TAG, e.toString());
}
};
new Thread(runnable).start();