From d0dc57695545a9926095df853a3932fca053a29b Mon Sep 17 00:00:00 2001 From: rikaaa0928 Date: Mon, 14 Oct 2024 15:18:54 +0800 Subject: [PATCH] wait net with CountDownLatch --- app/src/main/java/moe/rikaaa0928/uot/UogClient.kt | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/moe/rikaaa0928/uot/UogClient.kt b/app/src/main/java/moe/rikaaa0928/uot/UogClient.kt index bdf808e..a320a37 100644 --- a/app/src/main/java/moe/rikaaa0928/uot/UogClient.kt +++ b/app/src/main/java/moe/rikaaa0928/uot/UogClient.kt @@ -20,6 +20,7 @@ import java.net.DatagramSocket import java.net.InetAddress import java.net.SocketTimeoutException import java.net.URL +import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference @@ -30,7 +31,7 @@ class UogClient(val lPort: Int, val endpoint: String, val password: String) : Br var req: Channel? = null var udpSocket: AtomicReference = AtomicReference(null); private val stop = AtomicBoolean(true) - private val noNet = AtomicBoolean(false) + private val waitNet: AtomicReference = AtomicReference(null) private var lastAddr = "" private var lastPort = 0 private val bufferSize = 65535; @@ -115,7 +116,7 @@ class UogClient(val lPort: Int, val endpoint: String, val password: String) : Br Log.e("UpgClient", "grpc write", e) break } else { - if (noNet.get()) { + if (waitNet.get() != null) { Log.d("UogClient", "udp receive break no net: $id") break } @@ -135,8 +136,9 @@ class UogClient(val lPort: Int, val endpoint: String, val password: String) : Br } catch (e: Exception) { Log.e("UogClient", "all", e) } finally { - if (noNet.get()) { - TimeUnit.SECONDS.sleep(3) + val l = waitNet.get() + if (l != null) { + l.await() } else { TimeUnit.SECONDS.sleep(1) } @@ -180,9 +182,10 @@ class UogClient(val lPort: Int, val endpoint: String, val password: String) : Br capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) } if (!isWifiConnected && !isMobileDataConnected) { - noNet.set(true) + waitNet.compareAndSet(null, CountDownLatch(1)) } else { - noNet.set(false) + val l = waitNet.getAndSet(null) + l?.countDown() } } }