模拟器未从本地主机收到UDP数据包

时间:2019-08-26 13:27:20

标签: java android sockets android-emulator udp

我的应用在模拟器中运行时无法接收UDP数据包。 UDP数据包是通过以下Java程序在端口49999上的“ localhost”上发送的。

    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){}
        }

在同一本地主机上运行的另一个Java UDP服务器程序可以很好地接收数据包。这意味着数据包已正确发送到localhost:49999。

要将数据包从localhost转发到仿真器,我进行了telnet重定向,如下所示:

telnet localhost 49999
redir add udp:49999:49999

应用程序中的UDP接收器如下:

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){}

我的理解是telnet重定向应该负责将数据包从开发机器的localhost:49999转发到仿真器的localhost:49999,以便数据在DatagramSocket(49999)上可用。但是,它一直一直抛出SocketTimeoutException。

知道这里谜题缺少的内容将对您有很大的帮助。

1 个答案:

答案 0 :(得分:0)

连接到本地主机后,您可能需要检查cmd中的命令netstat -na是否确实按预期分配了端口。也可以尝试使用IP 127.0.0.1。