简体   繁体   中英

android udp receive is not working?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM