Android的UDP服务器没有收到数据包 [英] Android UDP server does not receive packets

查看:453
本文介绍了Android的UDP服务器没有收到数据包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code接收UDP数据包:

I have the following code to receive UDP packets:

public class AsyncReceiveUdp2 extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... f_url) {
    int udp=111;
    byte[] packet = new byte[2000];
    DatagramPacket dp = new DatagramPacket(packet, packet.length);
    DatagramSocket ds = null;
    try {
        ds = new DatagramSocket(udp);
        ds.receive(dp);
        //...
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ds != null) {
            ds.close();
        }
    }
    return null;
}

}

我从Android设备UDP数据发送到计算机。
电脑立即发送响应作为UDP数据包。
我资料储存到SD我的日志文件。
我看到,我的应用程序保持就行了ds.receive(DP);之后它不运行。
我对计算机上的程序在Android设备上进行测试。
据我了解是棘手的仿真器上接收UDP数据包。
我不能这样做。
因为它描述的重定向不为我工作这里

I send UDP data to computer from Android device. Computer immediately sends response as UDP packet. I save information to my log file on SD. And I see, that my app stays on the line "ds.receive(dp);" and does not run after it. I've tested on the Android device against a program on computer. As I understand it is tricky to receive UDP packets on Emulator. I could not do it. Redirect does not work for me as it is described here

另一个重要的问题是要接收的所有分组,已发送到该设备。无损。如何修改code是什么?

Another important issue is to receive all packets, that were sent to the device. Lossless. How to modify the code for that?

请帮帮忙!谢谢!

推荐答案

把你收到,而(真)循环中。当您收到分组呼叫一个if(pkg_received){打破;}任何你想做的事......或者......
问题是,你可能只能接收一个包,并接受它之前你得到超时。

put your receive inside a while(true) loop. When you receive a packet call an if (pkg_received){break;}... or whatever you want to do... The problem is that you are probably only be receiving one package and you are getting timeout before receiving it.

code编辑并没有经过测试。

Code edited and not tested

 while(true)
    {


        byte[] message = new byte[60*1024];
        DatagramPacket recv_packet = new DatagramPacket(message, message.length);


        try {
            socket.receive(recv_packet);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.d("UDP", "S: Receiving...listening on port " + recv_packet.getPort() );
        String rec_str;
        rec_str=new String(recv_packet.getData)

        Log.d("PACKAGE LENGTH",Integer.toString(recv_packet.getLength()));
}

这篇关于Android的UDP服务器没有收到数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆