0

I'm requesting data by sending a request command over UDP, and if it works, I'm supposed to receive a response. However, in the case that a response doesn't come through, I want to wait 3 seconds, then send a request again. I want to try this 3 times before "giving up" and displaying an error.

The code I have implemented is currently sending out the request once, but isn't sending it again one it realizes there is no response and I'm not sure where I'm going wrong.

int counter = 0;
static final int Limit = 3;

public void sendReq() {
new Thread((Runnable) () -> {
try {
    ...

    // Sending Request command here ...

    // Receiving
    while(true) {
        DatagramPacket dp = new DatagramPacket(buf, buf.length);
        socket.receive(dp);

        byte[] response = dp.getData();
        
        if(response.length == 0 || dp == null) {
            counter = counter + 1;
            if(counter == Limit) {
                // give up, display error
            } else {
                Thread.sleep(3000); // Wait 3 seconds
                sendReq();
            }
        } else {
            // Do stuff with response
        }

}
}

On the device I'm sending my command to, I made it so it holds its response on the first request, and I know the response isn't coming back. However my code isn't retrying.

What should I do?

  • `DatagramSocket.receive()` is a blocking call. I believe this is what you've experienced. Once the call is blocked, no retry can be performed. Try [this solution](https://stackoverflow.com/a/40055466/3290339). – Onik Dec 14 '20 at 21:26
  • @Onik Hmm, it doesn't seem like it's working, I don't think the try block is firing.. would you know why? All I did was add the try block with the socket.receive and added the SoTimeout after my socket initialization –  Dec 14 '20 at 22:29
  • _"I don't think the try block is firing"_ This only means you get an exception before the new `try {}` block. – Onik Dec 14 '20 at 22:40

0 Answers0