0

I am trying to make a UDP Listener listening to a server and receiving data.

Here is the UDPListener :

public class UDPListener extends AsyncTask<Void, String, Void>{
    public UDPConnector udpConnector;

    public UDPListener(UDPConnector udpConnector){
        byte[] buff;
    this.udpConnector = udpConnector;
    System.out.println("UDPListener initalized");
    }

    @Override
    protected Void doInBackground(Void... voidResult){
        Looper.prepare();
        while(true){
    
            byte[] buffer = new byte[512];
            DatagramPacket p = new DatagramPacket(buffer, buffer.length);
    
      

      try {
                System.out.println("Message reçu debug ");
                udpConnector.UDPSocket.receive(p);
                if(p.getData().length > 0){

                    buffer = p.getData();
                    String s = new String(buffer, 0, p.getLength());

                    publishProgress(s);
                }
            } catch (IOException e) {
                e.printStackTrace();

            }
        }
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        udpConnector.main.handleTextReceived(values[values.length-1]);
    }
}

The problem is publishProgress() never gets executed. I am sure that the UDPConnector is well configured because i can send data to the server. And i know that the method doInBackground is executed. I am also sure that the serveur is sending data to me as i can receive it with other tools.

I can post more code if needed, please let me know.

Thanks

Axel
  • 165
  • 3
  • 14

2 Answers2

1

If you are using the phone emulator, the emulator might be changing your expected IP address for which you will have to create a redirect. Look at this post

Datagram (UDP) receiver not working - not receiving broadcast packets

Assay
  • 96
  • 7
0

So, you don't initialize the socket with a specific port? which one is your server using for sending the datagrams? Maybe your problem is, that the socket is listening to a random port, which does not match to your port.

Indivon
  • 1,784
  • 2
  • 17
  • 32
  • It still doesn't work even if i initialize my DatagramSocket with the right port. I am sending data to the server on the 9001 port and i use the same DatagramSocket to listen to the server. – Axel Mar 11 '21 at 19:57
  • is your datagram at least 512 bytes long? the receive will not return unless the buffer is totally filled – Indivon Mar 11 '21 at 20:04
  • 2 other ideas: a) your firewall is blocking the requests. b) you have multiple networks/cards. you can try to set the InetAddress to 0.0.0.0 to listen on all – Indivon Mar 11 '21 at 20:25
  • @Indivon Nonsense. It will return as soon as one datagram has been received. The receive buffer should be *larger* than the largest expected datagram. – user207421 May 15 '21 at 22:09