UDP packets not received in emulator from localhost

旧街凉风 提交于 2019-12-02 15:57:34

问题


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.

来源:https://stackoverflow.com/questions/57658867/udp-packets-not-received-in-emulator-from-localhost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!