0

I'm trying to code a UDP client to receive packets from a server that is broadcasting on the local network. The problem is the receive method isn't blocking and waiting for a packet to arrive. Instead, it's receiving null or empty packets. I've tried to use .setSoTimeout(0), which supposedly will tell the receive to block until it receives a packet, but it doesn't.

Does anyone know how to fix this?

Here's the code:

 while (search == true) {

                InetAddress addr = InetAddress.getByName("0.0.0.0");
                DatagramSocket sock = new DatagramSocket(1355);
                sock.setSoTimeout(0);
                byte[] recebe = new byte[1024];
                sock.setBroadcast(true);


                System.out.println("entrou1");
                DatagramPacket packet = new DatagramPacket(recebe, recebe.length);

                System.out.println("entrou2");
                sock.receive(packet);
                String info = new String(packet.getData());
                System.out.println("tamanho: " + info.length());

                if (info.trim().equals("") == false && info != null) {
                    System.out.println("entrou aqui");
                    System.out.println("info recebida:" + info + ":fsadfsfs");
                    String servs[] = info.split("\n");
                    list1.clear();
                    servidores.clear();

                    for (int i = 0; i < servs.length; i++) {
                        System.out.println("vec: " + servs[i]);
                        if (servs[i].trim().equals("")) {
                            System.out.println("break;");
                            break;
                        } else {
                            String aux = servs[i].substring(0, servs[i].lastIndexOf("->"));
                            System.out.println("aux: " + aux);
                            list1.add(aux);
                            servidores.add(servs[i]);
                        }
                    }
                }



                System.out.println("info:\n" + info);

                sock.close();

                synchronized (obj) {
                    try {
                        obj.wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(AcederPartilhaGUI.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
4

0 回答 0