如何在android中等待一段时间后重试udp包请求

cvxl0en2  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(123)

我通过udp发送一个请求命令来请求数据,如果它起作用,我应该会收到一个响应。但是,如果响应没有通过,我希望等待3秒钟,然后再次发送请求。在“放弃”并显示错误之前,我想尝试3次。
我实现的代码目前只发送了一次请求,但没有再次发送一次,因为它意识到没有响应,我不知道我哪里出错了。

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
        }

}
}

在我向其发送命令的设备上,我这样做是为了在第一个请求时保留其响应,并且我知道响应不会返回。但是我的代码没有重试。
我该怎么办?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题