在UDP Socket java android上发送和接收数据
我能够通过UDP套接字正确发送我的数据,但是当我收到数据时,它会继续等待接收命令,我不知道是什么原因造成的。请看下面的代码。
我能够从Android设备在服务器端正确接收数据,但是当我从服务器端向Android设备发送数据时,它无法接收。但是当我将数据从服务器发送到任何其他客户端(例如PC应用程序)时,它会正确接收和显示数据。
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)
{
}
}
}