套接字总是收到最后一个udp数据包

时间:2015-04-14 23:15:22

标签: android sockets

总是我可以得到第一个udp数据包,但是当我收到第二个udp数据包时,DatagramPacket总是得到最后一个数据包的一部分。

例如: 我需要收到第一个包:“AAAAAAAAAA” 我收到:“AAAAAAAAAA”

我需要在第二个数据包中收到:“BBBB” 我收到了:“BBBBAAAA”。

我如何刷新,擦除或其他方法来解决我的问题?

这是我的代码:

public DatagramServer(Context c, Activity a) throws SocketException {
        setSocket(new DatagramSocket(Constantes.UDP_PORT));
        getSocket().setBroadcast(true);     
        getSocket().setReuseAddress(true);
        setContext(c);
        setActivity(a);
        Thread thread = new Thread(new Runnable() {
        @Override
            public void run() {
                try {
                    receivePacket();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        thread.start();

    }

public void receivePacket() throws IOException {
        byte[] buf = null;
        buf = new byte[Constantes.PACKETSIZE];
        final DatagramPacket packet = new DatagramPacket(buf, buf.length);

        while (true) {

            getSocket().receive(packet);

            Handler mainHandler = new Handler(getContext().getMainLooper());
            Runnable myRunnable = new Runnable() {
                @Override
                public void run() {
                    byte[] resposta = packet.getData();
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                    if (resposta[0] == 111) {

                        if (GlobalSingleton.getInstance().is_pode_reconhecer_central()){

                            final CentralDAO cDAO = new CentralDAO(getContext());

                            final Central central = new Central();
                            Central centralExistente = new Central();
                            Boolean bcentralExiste = false;
                            central.set_IP(packet.getAddress().getHostAddress());
                            central.set_mac(CentralService.getMAC(packet.getData()));
                            central.set_modificado(true);
                            central.set_ativo(true);


                            }
                            else {
                                centralExistente.set_IP(packet.getAddress().getHostAddress());
                                centralExistente.set_ativo(true);

                                for (int i=0;i<lvCentrais.getCount();i++){
                                    Central centrallv = (Central) lvCentrais.getItemAtPosition(i);
                                    if (centrallv.get_mac().equals(centralExistente.get_mac())){
                                        centrallv.set_IP(centralExistente.get_IP());
                                        centrallv.set_ativo(centralExistente.is_ativo());
                                    }
                                }

                            }

                            GlobalSingleton.getInstance().set_pode_reconhecer_central(false);
                        }

                    } else {
                        String respostaString = "";
                        try {
                            respostaString = new String(packet.getData(),"ASCII");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }//new String(packet.getData(),packet.getOffset(),packet.getLength());//

                        if (respostaString.toUpperCase().contains(Constantes.ANSWER_DEVICE)) {

                            if (GlobalSingleton.getInstance().is_pode_reconhecer_dispositivo()){

                                final GeradorDAO gerDAO = new GeradorDAO(getContext());
                                final DispositivoDAO dDAO = new DispositivoDAO(getContext());

                                List<Gerador> list = gerDAO.selectAll();

                                if (list.size()>0){

                                    int mac,versao,tipo;

                                    String values[] = Utils.getValorString(respostaString, Constantes.P_COMA, Constantes.P_INDICADOR);

                                    mac = Integer.parseInt(values[0].trim());
                                    tipo = Integer.parseInt(values[1].trim());
                                    versao = Integer.parseInt(values[2].trim());

                                    if (dDAO.selectOne(mac, GlobalSingleton.getInstance().get_current_central().get_id()) == null){

                                        final Gerador gerador = gerDAO.selectOne(tipo, versao);                                 
                                        final Dispositivo dispNovo = new Dispositivo(GlobalSingleton.getInstance().get_current_central().get_id());

                                        dispNovo.set_mac(mac);
                                        dispNovo.set_tipo(tipo);
                                        dispNovo.set_versao(versao);

                                        dispNovo.set_nome(gerador.get_nome_dispositivo());


                                    }
                                    else{
                                        Toast.makeText(getContext(), "Dispositivo já existe", Toast.LENGTH_SHORT).show();
                                    }                       

                                }

                                GlobalSingleton.getInstance().set_pode_reconhecer_dispositivo(false);
                            }                           
                        }

                    }               
                }
            };
            mainHandler.post(myRunnable);

        }
    }

我是android的初学者,如果你能帮助我,我会很感激!

1 个答案:

答案 0 :(得分:1)

你忽略了DatagramPacket.

中的长度
central.set_mac(CentralService.getMAC(packet.getData()))

应该是

central.set_mac(CentralService.getMAC(packet.getData(), packet.getOffset(), packet.getLength()))

假设getMac()方法接受这些参数。否则,您必须自己创建一个适当大小的字节数组。

编辑我不打算在packet.getData().

的其他每次使用中重复这一点