简体   繁体   中英

UDP packets not received in emulator from localhost

My app is unable to receive the UDP packets when running in the emulator. UDP packets are sent by below java program on "localhost" over the port 49999.

    DatagramSocket clientsocket;
        DatagramPacket dp;
        BufferedReader br;
        InetAddress ia;
        byte buf[] = new byte[1024];
        int cport = 50000, sport = 49999;

        clientsocket = new DatagramSocket(cport);
        dp = new DatagramPacket(buf, buf.length);
        br = new BufferedReader(new InputStreamReader(System.in));
        ia = InetAddress.getLocalHost();

        while(true)
        {
            Random rand = new Random();
            String str1 = rand.nextInt(100) + "";
            buf = str1.getBytes();

            System.out.println("Sending " + str1);
            clientsocket.send(new DatagramPacket(buf,str1.length(), ia, sport));

            try{
                Thread.sleep(100);
            } catch(Exception e){}
        }

Another java UDP server program running on the same localhost receives the packets fine. This means that the packets are sent to localhost:49999 correctly.

To forward the packets from localhost to the emulator, I did telnet redirect as below:

telnet localhost 49999
redir add udp:49999:49999

The UDP receiver in the app looks like this:

byte[] data = new byte[1400];
DatagramPacket packet = new DatagramPacket(data, 1400);
DatagramSocket socket = new DatagramSocket(49999);
socket.setSoTimeout(200);
try{
socket.receive(packet);  ---->> This throws a SocketTimeoutException
} catch(SocketTimeoutException e){}

My understanding was that the telnet redirect should take care of forwarding the packets from my development machine's localhost:49999 to emulator's localhost:49999 so that the data is available on the DatagramSocket(49999). However it keeps throwing the SocketTimeoutException all the time.

It would be a great help to know what is the missing piece of the puzzle here.

After connecting to the localhost you may want to check that the port was actually asigned as intended with the command netstat -na in the cmd. It also might be worth a try to use the IP 127.0.0.1 instead.

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