I try to send udp data from PC and receive the data in android emulator. If we send data from android to PC it’s working perfectly. But android emulator not receives the udp data .How to receive data in android.
This is my UDP sending code :
class WriteSender {
public static void main(String args[]) throws Exception {
int serverPort = 998;
int buffer_size = 1024;
byte buffer[] = new byte[buffer_size];
System.out.println("Enter String to send ");
DatagramSocket ds = new DatagramSocket(serverPort);
int pos = 0;
while (true) {
int c = System.in.read();
switch (c) {
case -1:
System.out.println("Server Quits.");
return;
case '\r':
break;
case '\n':
ds.send(new DatagramPacket(buffer, pos, InetAddress.getByName("10.0.2.15"), 5757));
pos = 0;
开发者_运维百科 break;
default:
buffer[pos++] = (byte) c;
}
}
}
}
This is my UDP Receive code:
public class Server implements Runnable {
public static final String SERVERIP="10.0.2.15";
public static final int SERVERPORT = 5757;
private DatagramSocket ds;
@Override
public void run() {
int buffer_size = 1024;
byte buffer[] = new byte[buffer_size];
Log.d("MY UDP ","Before create");
try {
ds = new DatagramSocket(SERVERPORT);
while (true) {
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
ds.receive(p);
Log.d("MY UDP ",new String(p.getData(), 0, p.getLength()));
}
}
catch(Exception e){
Log.e("MY UDP ", " Error", e);
}
}
}
Redirect :
telnet localhost 5554
redir add udp:998:5757
How to receive udp data? Am I did anything wrong in my code ?
Android on emulator does not receives packet because it is in another network. It works as virtual system on you PC and creates own network
You can read more in this topic for example here android emulator and networking
May I recommend having a look at the Java example here: http://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
Its not Android-specific but their code description should explain everything you need to know here.
精彩评论