I am able to properly send my data through UDP socket , but when I receive data it keeps on waiting at receive command I don't know what is causing this. Please have a look at my code below.
I am able to properly receive data at server side from android device, but when I send data from server side to android device it doesn't receive. but when I send data from server to any other client e.g PC application it receive and displays data properly.
class Task implements Runnable {
@Override
public void run() {
try {
String messageStr = "feed";
int server_port = 8888;
InetAddress local = InetAddress.getByName("10.0.2.2");
int msg_length = messageStr.length();
byte[] message = messageStr.getBytes();
DatagramSocket s = new DatagramSocket();
//
DatagramPacket p = new DatagramPacket(message, msg_length, local, server_port);
s.send(p);//properly able to send data. i receive data to server
for (int i = 0; i <= 20; i++) {
final int value = i;
message = new byte[30000];
p = new DatagramPacket(message,message.length );
s.receive(p); //keeps on waiting here but i am sending data back from server, but it never receives
final byte[] data = p.getData();;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
@Override
public void run() {
progressBar.setProgress(value);
imageView.setImageBitmap(BitmapFactory.decodeByteArray(data,0,data.length));
}
});
}
}
catch(Exception ex)
{
}
}
}
Here, in this post you will find the detailed code for establishing socket between devices or between two application in the same mobile.
You have to create two application to test below code.
In both application's manifest file, add below permission
activity_main.xml
UDPClientSocketActivity.java
activity_main.xml
UDPServerSocketActivity.java
Documentation in Eclipse:
The "
s.receive(p);
" command blocks the thread until it receices data or the timeout set with setSoTimeout(timeout) is over.I have made 2 classes to make my communication happen. First UDP-Server:
I send the received data to an BroadcastReceiver and there you can do what ever you want to with the data.
And now my client to send the data. In this code I send a broadcast, but I think it will be no problem to change the code for sending to a direct IP or something.
And here is how you instantiate the classes from your main class.
And here how to send a message with the client.
To stop the UDP_Server, just set Server.Server_aktiv to false.
To set the message above u can also write a "setMessage(String message)" methode or something like that.